package com.yuncheng.spcyApi.busService;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.deepoove.poi.data.TextRenderData;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.config.ConfigureBuilder;
import com.deepoove.poi.data.PictureRenderData;
import com.deepoove.poi.data.PictureType;
import com.deepoove.poi.data.Pictures;
import com.deepoove.poi.policy.HackLoopTableRenderPolicy;
import com.yuncheng.spcyApi.config.SpcyMinioUtils;
import com.yuncheng.spcyApi.constant.common.BusinessConstant;
import com.yuncheng.spcyApi.constant.common.LogConstant;
import com.yuncheng.spcyApi.constant.common.SpcyCommonConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.constant.wjml.WjmlConstant;
import com.yuncheng.spcyApi.constant.xcjchy.SqsxHyConstant;
import com.yuncheng.spcyApi.entity.*;
import com.yuncheng.exception.BusinessException;
import com.yuncheng.spcyApi.service.*;
import com.yuncheng.spcyApi.utils.*;
import com.yuncheng.vo.HttpResult;
import com.yuncheng.spcyApi.vo.common.HttpResultVo;
import com.yuncheng.spcyApi.vo.common.Result;
import com.yuncheng.spcyApi.vo.sqsx.SqsxZbrVo;
import com.yuncheng.spcyApi.vo.wjmb.SqsxWjmbVo;
import com.yuncheng.spcyApi.vo.xcjchy.SqsxHyXcjcqdbVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import utils.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;

@Component(value = "initWjjlService")
public class InitWjjlService {

    private static final Logger log = LoggerFactory.getLogger(InitWjjlService.class);

    @Resource
    @Lazy
    private ISpcySqsxBaiscService spcySqsxBaiscService;

    @Resource
    @Lazy
    private ISpcySqsxWjjlService spcySqsxWjjlService;

    @Resource
    private ISpcySqsxXpjlService spcySqsxXpjlService;

    @Resource
    @Lazy
    private ISpcyRsWjmbService spcyRsWjmbService;

    @Resource
    @Lazy
    private BusService busService;

    @Resource
    @Lazy
    private ISpcyLogService spcyLogService;

    @Resource
    private BusinessConstant businessConstant;

    @Resource
    private LocalFileUploadUtils localFileUploadUtils;

    @Resource
    private SpcyMinioUtils spcyMinioUtils;

    @Resource
    private HnCaUtils hnCaUtils;

    @Resource
    @Lazy
    private ISpcyRsYwzdxxService spcyRsYwzdxxService;

    @Autowired
    @Qualifier("asyncMiddleTask")
    private Executor executor;

    /**
     * 批量删除申请事项文件材料-任务登记
     */
    public void batchDeleteRwdjSqsxWj(String sqsxid){
        List<SpcySqsxWjjl> list = spcySqsxWjjlService.list(new LambdaQueryWrapper<SpcySqsxWjjl>()
                .eq(SpcySqsxWjjl::getFpid, sqsxid));
        if (CollectionUtil.isEmpty(list)){
            return;
        }

        String log = "";
        for (SpcySqsxWjjl bean : list){
            if (org.apache.commons.lang3.StringUtils.isNotBlank(bean.getFcflj())) {
                localFileUploadUtils.deleteLocalFileUrl(bean.getFcflj());
            }
            if (org.apache.commons.lang3.StringUtils.isNotBlank(bean.getFjdcflj())){
                localFileUploadUtils.deleteLocalFileUrl(bean.getFjdcflj());
            }

            log = "";
            log = "批量删除申请事项文件材料-任务登记：";
            log += LogUtils.MapToStringMethod(ObjectToMapUtils.objectToMap(bean));
            spcyLogService.addLogs(LogConstant.LOGS_SQSX_BASIC, log, sqsxid, "批量删除申请事项文件材料-任务登记", SpcyConstant.LOGS_SYS_TYPE_SC);
        }

        spcySqsxWjjlService.remove(new LambdaQueryWrapper<SpcySqsxWjjl>()
                .eq(SpcySqsxWjjl::getFpid, sqsxid));
    }

    /**
     * 下载申请文件模板
     * @param wjmbId 文件模板id
     * @param sqsxid 申请事项id
     * @param type 文件模板类型
     * @param response
     */
    public void downloadSqsxFileMb(String wjmbId, String sqsxid, String type, HttpServletResponse response) throws IOException {
        if (StringUtils.isBlank(sqsxid)){
            response.setContentType("text/html");
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.println("下载失败！事项参数为空！");
            writer.close(); // 不要忘记关闭PrintWriter

            return;
        }

        SpcySqsxBasic sqsx = spcySqsxBaiscService.getById(sqsxid);
        if (sqsx == null){
            response.setContentType("text/html");
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.println("下载失败！没有相匹配的事项！");
            writer.close(); // 不要忘记关闭PrintWriter

            return;
        }

        String fywflcode = sqsx.getFywflcode();

        String wjmbUrl = ""; // 模板路径
        SqsxWjmbVo wjmbBySqsxId = busService.getWjmbBySqsxId(wjmbId, sqsxid, sqsx, fywflcode, type);
        if (wjmbBySqsxId != null && StringUtils.isBlank(wjmbBySqsxId.getErrorMsg())){
            wjmbUrl = wjmbBySqsxId.getWjmbUrl();

        }else {
            log.error(wjmbBySqsxId.getErrorMsg());

            response.setContentType("text/html");
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.println(wjmbBySqsxId.getErrorMsg());
            writer.close(); // 不要忘记关闭PrintWriter

            return;
        }

        String destUrl = ""; //保存路径
        String wjlx = Util.getWjHz(wjmbUrl); // 获取文件路径的 文件类型
        String formatType = BusinessConstant.getWordFormatType(wjlx); // word替换格式

        Map<String,String> map = busService.getObjectMap(sqsxid, sqsx, ""); // 获取替换相关内容

        destUrl = localFileUploadUtils.getTempFileRootUrl() + "/"; // 保存路径
        destUrl += GetUuIdUtils.NotReplaceUuId() + wjlx;

        InsertAndOutWordUtils.wordTextSubstitution(wjmbUrl, destUrl, formatType, map); // word关键字替换文本,并生成新文件

        localFileUploadUtils.ejzLocalFileByZdyFile(new File(destUrl), response);
    }

    /**
     * 下载申请文件模板-下载到本地
     * @param wjmbId 文件模板id
     * @param sqsxid 申请事项id
     * @param type 文件模板类型
     */
    public String downloadSqsxWjmbToLocal(String wjmbId, String sqsxid, String type, SpcySqsxBasic sqsx){
        if (StringUtils.isBlank(sqsxid)){
            return "";
        }

        if (sqsx == null) {
            sqsx = spcySqsxBaiscService.getById(sqsxid);
            if (sqsx == null) {
                return "";
            }
        }
        String fywflcode = sqsx.getFywflcode();

        String wjmbUrl = ""; // 模板路径
        SqsxWjmbVo wjmbBySqsxId = busService.getWjmbBySqsxId(wjmbId, sqsxid, sqsx, fywflcode, type);
        if (wjmbBySqsxId != null && StringUtils.isBlank(wjmbBySqsxId.getErrorMsg())){
            wjmbUrl = wjmbBySqsxId.getWjmbUrl();

        }else {
            log.error("下载申请文件模板-下载到本地错误: {}", wjmbBySqsxId.getErrorMsg());
            return "";
        }

        String destUrl = ""; //保存路径
        String wjlx = Util.getWjHz(wjmbUrl); // 获取文件路径的 文件类型
        String formatType = BusinessConstant.getWordFormatType(wjlx); // word替换格式

        Map<String,String> map = new HashMap<>();
        map = busService.getObjectMap(sqsxid, sqsx,""); // 获取替换相关内容

        destUrl = localFileUploadUtils.getTempFileRootUrl() + "/"; // 保存路径
        destUrl += GetUuIdUtils.NotReplaceUuId() + wjlx;

        try {
            InsertAndOutWordUtils.wordTextSubstitution(wjmbUrl, destUrl, formatType, map); // word关键字替换文本,并生成新文件
        }catch (Exception e){
            log.error("模板错误：{}",e.getMessage());

            return wjmbUrl;
        }


        return destUrl;
    }

    /**
     * 下载文件库模板-到本地
     */
    public String downRsWjmbToLocal(String wjmbId, String sqsxid, String type, SpcySqsxBasic sqsx){

        String fywflcode = sqsx.getFywflcode();
        String wjmbUrl = ""; // 模板路径
        SqsxWjmbVo wjmbBySqsxId = busService.getWjmbBySqsxId(wjmbId, sqsxid, sqsx, fywflcode, type);
        if (wjmbBySqsxId != null && StringUtils.isBlank(wjmbBySqsxId.getErrorMsg())){
            wjmbUrl = wjmbBySqsxId.getWjmbUrl();

        }else {
            log.error("下载申请文件模板-下载到本地错误: {}", wjmbBySqsxId.getErrorMsg());
            return "";
        }

        return wjmbUrl;
    }

    /**
     * 上传申请文件
     * @param sqsxid 申请事项id
     * @param type 模板类型
     * @param // fwjxsmc 文件显示名称
     * @param isOnlyPdf true: 不能上传文档类型文件
     */
    public void uploadSqsxFile(MultipartFile[] uploadFile, String sqsxid, String type, boolean isOnlyPdf){
        this.uploadSqsxFile(uploadFile, sqsxid, type, "", isOnlyPdf);
    }

    public void uploadSqsxFile(MultipartFile[] uploadFile, String sqsxid, String type, String fwjxsmc, boolean isOnlyPdf){
        this.uploadCommonFile(uploadFile, sqsxid, type, "", fwjxsmc, isOnlyPdf);
    }

    /** 通用文件上传 */
    public void uploadCommonFile(MultipartFile[] uploadFile, String sqsxid, String type, String wjlx2, String fwjxsmc, boolean isOnlyPdf){
        this.uploadCommonFile(uploadFile, sqsxid, type, wjlx2, fwjxsmc, "", isOnlyPdf);
    }

    public void uploadCommonFile(MultipartFile[] uploadFile, String sqsxid, String type, String wjlx2, String fwjxsmc, String wjid, boolean isOnlyPdf){
        this.uploadCommonFile(uploadFile, sqsxid, type, wjlx2, fwjxsmc, wjid, isOnlyPdf, "");
    }

    /** 通用文件上传 */
    public void uploadCommonFile(MultipartFile[] uploadFile, String sqsxid, String type, String wjlx2, String fwjxsmc, String wjid, boolean isOnlyPdf, String fwjnr){

        for (MultipartFile file : uploadFile) {

            SpcySqsxWjjl spcySqsxWjjl = new SpcySqsxWjjl();

            String originalFilename = file.getOriginalFilename();

            // 文件类型
            String wjlx = originalFilename.substring(originalFilename.lastIndexOf("."));
            wjlx = wjlx.toLowerCase();

            if (isOnlyPdf && (wjlx.equalsIgnoreCase(".doc") || wjlx.equalsIgnoreCase(".docx"))){
                throw new BusinessException("请上传pdf文件/图片！");
            }

            // 文件名
            String fileName = "";

            if (StringUtils.isBlank(fwjxsmc)) {
                // 文件名
                fileName = originalFilename.substring(0, originalFilename.lastIndexOf("."));
                if (StringUtils.isNotBlank(type)) {
                    fileName = type + "-" + fileName;
                }
            }else {
                fileName = type + "-" +fwjxsmc;
            }
            if (StringUtils.isBlank(wjid)){
                wjid = GetUuIdUtils.ReplaceUuId();
            }
            spcySqsxWjjl.setId(wjid);
            spcySqsxWjjl.setFwjxsmc(fileName); // 文件显示名称

            String wjccmc = spcySqsxWjjl.getId() + wjlx;

            String wjml = DateConversionUtils.DateToMonthTwo(new Date());
//            localFileUploadUtils.uploadSqsxFile(file, wjml, wjccmc); // 上传文件

            spcySqsxWjjl.setFpid(sqsxid);
            spcySqsxWjjl.setFwjlx(wjlx);
            spcySqsxWjjl.setFwjlx1(type);
            spcySqsxWjjl.setFwjccmc(wjccmc);
            String cflj = "/" + wjml + "/" + wjccmc;
            spcySqsxWjjl.setFcflj(cflj);

            spcySqsxWjjl.setFwjlx2(wjlx2);

            /**笔录 图片标识*/
            boolean isCompressFile = false;
            if (type.equals(WjmlConstant.xcjcbl_jcgcjl)){
                if (StringUtils.isBlank(fwjnr)) {
                    if (Util.verifyIsImageByWjhz(wjlx)) {
                        fwjnr = "1"; // 图片标识
                        isCompressFile = true;
                    } else {
                        fwjnr = "0";
                    }
                }else if (Util.verifyIsImageByWjhz(wjlx)){
                    isCompressFile = true;
                }
            }

            boolean uploadFlag = false;
            if (isCompressFile){
                File compressImage = localFileUploadUtils.compressImage(file);
                if (compressImage == null){
                    if (localFileUploadUtils.uploadSqsxFile(file, wjml, wjccmc) != null) { // 上传文件
                        uploadFlag = true;
                    }
                }else {
                    uploadFlag = spcyMinioUtils.putFlagFile(localFileUploadUtils.getSqsxWjjlRelativeUrl(cflj), compressImage, wjlx);
                    LocalFileUploadUtils.deleteAbsFile(compressImage);
                }
            }else {
                if (localFileUploadUtils.uploadSqsxFile(file, wjml, wjccmc) != null) { // 上传文件
                    uploadFlag = true;
                }
            }

            spcySqsxWjjl.setFwjnr(fwjnr);

            /** 文档兼容可以在线编辑 */
            if (wjlx.equalsIgnoreCase(".doc") || wjlx.equalsIgnoreCase(".docx")){
                spcySqsxWjjl.setFwjlx3(SpcyCommonConstant.SQSX_WJJL_TYPE3_ZZZ);
            }else {
                spcySqsxWjjl.setFwjlx3(SpcyCommonConstant.SQSX_WJJL_TYPE3_YWC2);
                spcySqsxWjjl.setFwjlx4(SpcyCommonConstant.SQSX_WJJL_TYPE4_SDSC);
            }

            /** 企业、中心标识 */
            if (GetCurrentUserUtils.getCurrentUserOrgId().equals(SpcyConstant.QY_ORG_ID)) {
                spcySqsxWjjl.setFwjlx7(SpcyConstant.QY_SQSX_WJJL_UPLOAD_FLAG);
            }else {
                spcySqsxWjjl.setFwjlx7(GetCurrentUserUtils.getCurrentUserId());
            }

            if (uploadFlag) {
                spcySqsxWjjlService.save(spcySqsxWjjl);
                wjid = "";

                String czContent = "上传文件-" + fileName + ": ";
                Map<String, Object> wjjlMap = ObjectToMapUtils.objectToMap(spcySqsxWjjl);
                czContent += LogUtils.MapToStringMethod(wjjlMap);
                spcyLogService.addLogs(LogConstant.LOGS_SQSX_WJJL, czContent, sqsxid, "上传文件", SpcyConstant.LOGS_SYS_TYPE_BC);
            }
        }

    }

    /** 通用文件上传 */
    public String uploadCommonParts(Collection<Part> parts, String sqsxid, String type, String wjlx2, String fwjxsmc, String wjid, boolean isOnlyPdf, String fwjnr){
        List<File> fileList = new ArrayList<>(parts.size());
        for (Part part : parts) {
            try {
                String fileName = Paths.get(part.getSubmittedFileName()).getFileName().toString();
                String wjHz = Util.getWjHz(fileName);

                if (isOnlyPdf && (wjHz.equalsIgnoreCase(".doc") || wjHz.equalsIgnoreCase(".docx"))) {
                    return "请上传pdf文件/图片！";
                }

                File file = localFileUploadUtils.uploadDempFile(part, GetUuIdUtils.NotReplaceUuId() + wjHz);
                if (file != null) {
                    fileList.add(file);
                }
            }catch (Exception e){
                continue;
            }
        }

        this.uploadCommonFile(fileList, sqsxid, type, wjlx2, fwjxsmc, wjid, isOnlyPdf, fwjnr);

        return null;
    }

    /** 通用文件上传 */
    public void uploadCommonFile(List<File> fileList, String sqsxid, String type, String wjlx2, String fwjxsmc, String wjid, boolean isOnlyPdf, String fwjnr){
        for (File file : fileList) {
            SpcySqsxWjjl spcySqsxWjjl = new SpcySqsxWjjl();

            String originalFilename = file.getName();

            // 文件类型
            String wjlx = originalFilename.substring(originalFilename.lastIndexOf("."));
            wjlx = wjlx.toLowerCase();

            if (isOnlyPdf && (wjlx.equalsIgnoreCase(".doc") || wjlx.equalsIgnoreCase(".docx"))) {
                throw new BusinessException("请上传pdf文件/图片！");
            }

            // 文件名
            String fileName = "";

            if (StringUtils.isBlank(fwjxsmc)) {
                // 文件名
                fileName = originalFilename.substring(0, originalFilename.lastIndexOf("."));
                if (StringUtils.isNotBlank(type)) {
                    fileName = type + "-" + fileName;
                }
            } else {
                fileName = type + "-" + fwjxsmc;
            }
            if (StringUtils.isBlank(wjid)) {
                wjid = GetUuIdUtils.ReplaceUuId();
            }
            spcySqsxWjjl.setId(wjid);
            spcySqsxWjjl.setFwjxsmc(fileName); // 文件显示名称

            String wjccmc = spcySqsxWjjl.getId() + wjlx;

            String wjml = DateConversionUtils.DateToMonthTwo(new Date());

            spcySqsxWjjl.setFpid(sqsxid);
            spcySqsxWjjl.setFwjlx(wjlx);
            spcySqsxWjjl.setFwjlx1(type);
            spcySqsxWjjl.setFwjccmc(wjccmc);
            String cflj = "/" + wjml + "/" + wjccmc;
            spcySqsxWjjl.setFcflj(cflj);

            spcySqsxWjjl.setFwjlx2(wjlx2);

            /**笔录 图片标识*/
            boolean isCompressFile = false;
            if (type.equals(WjmlConstant.xcjcbl_jcgcjl)) {
                if (StringUtils.isBlank(fwjnr)) {
                    if (Util.verifyIsImageByWjhz(wjlx)) {
                        fwjnr = "1"; // 图片标识
                        isCompressFile = true;
                    } else {
                        fwjnr = "0";
                    }
                } else if (Util.verifyIsImageByWjhz(wjlx)) {
                    isCompressFile = true;
                }
            }

            boolean uploadFlag = false;
            if (isCompressFile) {
                File compressImage = localFileUploadUtils.compressImage(file);
                if (compressImage == null) {
                    if (localFileUploadUtils.isEnableMinioWjjlFile()){
                        uploadFlag = spcyMinioUtils.putFlagFile(localFileUploadUtils.getSqsxWjjlRelativeUrl(cflj), file, wjlx);
                    }else {
                        uploadFlag = FileCopyUtils.copyFile(compressImage.getAbsolutePath(), localFileUploadUtils.getSqsxWjjlAbsUrl(cflj));
                    }
                } else {
                    if (localFileUploadUtils.isEnableMinioWjjlFile()) {
                        uploadFlag = spcyMinioUtils.putFlagFile(localFileUploadUtils.getSqsxWjjlRelativeUrl(cflj), compressImage, wjlx);
                    }else {
                        uploadFlag = FileCopyUtils.copyFile(compressImage.getAbsolutePath(), localFileUploadUtils.getSqsxWjjlAbsUrl(cflj));
                    }
                    LocalFileUploadUtils.deleteAbsFile(compressImage);
                }
            } else {
                if (localFileUploadUtils.isEnableMinioWjjlFile()) {
                    uploadFlag = spcyMinioUtils.putFlagFile(localFileUploadUtils.getSqsxWjjlRelativeUrl(cflj), file, wjlx);
                }else {
                    uploadFlag = FileCopyUtils.copyFile(file.getAbsolutePath(), localFileUploadUtils.getSqsxWjjlAbsUrl(cflj));
                }
            }

            spcySqsxWjjl.setFwjnr(fwjnr);

            /** 文档兼容可以在线编辑 */
            if (wjlx.equalsIgnoreCase(".doc") || wjlx.equalsIgnoreCase(".docx")) {
                spcySqsxWjjl.setFwjlx3(SpcyCommonConstant.SQSX_WJJL_TYPE3_ZZZ);
            } else {
                spcySqsxWjjl.setFwjlx3(SpcyCommonConstant.SQSX_WJJL_TYPE3_YWC2);
                spcySqsxWjjl.setFwjlx4(SpcyCommonConstant.SQSX_WJJL_TYPE4_SDSC);
            }

            /** 企业、中心标识 */
            if (GetCurrentUserUtils.getCurrentUserOrgId().equals(SpcyConstant.QY_ORG_ID)) {
                spcySqsxWjjl.setFwjlx7(SpcyConstant.QY_SQSX_WJJL_UPLOAD_FLAG);
            } else {
                spcySqsxWjjl.setFwjlx7(GetCurrentUserUtils.getCurrentUserId());
            }

            if (uploadFlag) {
                spcySqsxWjjlService.save(spcySqsxWjjl);

                wjid = "";
                LocalFileUploadUtils.deleteAbsFile(file);

                String czContent = "上传文件-" + fileName + ": ";
                Map<String, Object> wjjlMap = ObjectToMapUtils.objectToMap(spcySqsxWjjl);
                czContent += LogUtils.MapToStringMethod(wjjlMap);
                spcyLogService.addLogs(LogConstant.LOGS_SQSX_WJJL, czContent, sqsxid, "上传文件", SpcyConstant.LOGS_SYS_TYPE_BC);
            }

        }
    }

    /**
     * 删除并上传文件
     * */
    public void deleteUploadSqsxFile(MultipartFile[] uploadFile, String sqsxid, String type, String fwjxsmc, boolean isOnlyPdf){

        List<SpcySqsxWjjl> oldWjList = spcySqsxWjjlService.list(new LambdaQueryWrapper<SpcySqsxWjjl>()
                .eq(SpcySqsxWjjl::getFpid, sqsxid)
                .eq(SpcySqsxWjjl::getFwjlx1, type));
        for (SpcySqsxWjjl oldWjjl : oldWjList) {
            spcySqsxWjjlService.removeById(oldWjjl.getId());

            if (StringUtils.isNotBlank(oldWjjl.getFcflj())) {
                localFileUploadUtils.deleteLocalFileUrl(oldWjjl.getFcflj());
            }
            if (StringUtils.isNotBlank(oldWjjl.getFjdcflj())) {
                localFileUploadUtils.deleteLocalFileUrl(oldWjjl.getFjdcflj());
            }
        }

        this.uploadSqsxFile(uploadFile, sqsxid, type, fwjxsmc, isOnlyPdf);
    }

    /**
     * 替换-上传的申请事项文件
     * @param fileid 旧的文件记录id
     * @param isOnlyPdf true: 不能上传文档类型文件
     * @param isDeleteFileId 是否删除旧的文件
     */
    public void replaceUploadSqsxFile(MultipartFile[] uploadFile,String fileid,boolean isOnlyPdf, boolean isDeleteFileId){
        if (uploadFile == null || uploadFile.length == 0) {
            throw new BusinessException("上传失败,请先选择文件！");
        }

        if (StringUtils.isEmpty(fileid)){
            throw new BusinessException("文件参数为空！");
        }

        SpcySqsxWjjl oldWjjl = spcySqsxWjjlService.getById(fileid);
        if (oldWjjl == null){
            throw new BusinessException("没有相匹配的文件数据！");
        }

        for (MultipartFile file : uploadFile) {

            SpcySqsxWjjl spcySqsxWjjl = new SpcySqsxWjjl();
            spcySqsxWjjl.setId(GetUuIdUtils.ReplaceUuId());

            String originalFilename = file.getOriginalFilename();

            // 文件类型
            String wjlx = originalFilename.substring(originalFilename.lastIndexOf("."));
            wjlx = wjlx.toLowerCase();

            if (isOnlyPdf && (wjlx.equals(".doc") || wjlx.equals(".docx"))){
                throw new BusinessException("请上传pdf文件/图片！");
            }

            // 文件名
//            String fileName = originalFilename.substring(0, originalFilename.lastIndexOf("."));
            String wjccmc = spcySqsxWjjl.getId() + wjlx;

            String wjml = DateConversionUtils.DateToMonthTwo(new Date());
            localFileUploadUtils.uploadSqsxFile(file, wjml, wjccmc); // 上传文件

            // 新文件替换旧文件
            spcySqsxWjjl.setFwjxsmc(oldWjjl.getFwjxsmc());
            spcySqsxWjjl.setFpid(oldWjjl.getFpid());
            spcySqsxWjjl.setFwjlx1(oldWjjl.getFwjlx1());
            spcySqsxWjjl.setFwjlx6(oldWjjl.getFwjlx6());

            spcySqsxWjjl.setFwjlx(wjlx);
            spcySqsxWjjl.setFwjccmc(wjccmc);
            String cflj = "/" + wjml + "/" + wjccmc;
            spcySqsxWjjl.setFcflj(cflj);

            /** 文档兼容可以在线编辑 */
            if (wjlx.equalsIgnoreCase(".doc") || wjlx.equalsIgnoreCase(".docx")){
                spcySqsxWjjl.setFwjlx3(SpcyCommonConstant.SQSX_WJJL_TYPE3_ZZZ);
            }else {
                spcySqsxWjjl.setFwjlx3(SpcyCommonConstant.SQSX_WJJL_TYPE3_YWC2);
                spcySqsxWjjl.setFwjlx4(SpcyCommonConstant.SQSX_WJJL_TYPE4_SDSC);
            }

            /*spcySqsxWjjl.setFwjlx3(SpcyCommonConstant.SQSX_WJJL_TYPE3_YWC2);
            spcySqsxWjjl.setFwjlx4(SpcyCommonConstant.SQSX_WJJL_TYPE4_SDSC);*/

            spcySqsxWjjlService.save(spcySqsxWjjl);

            String czContent = "上传文件-"+originalFilename+": ";
            Map<String, Object> wjjlMap = ObjectToMapUtils.objectToMap(spcySqsxWjjl);
            czContent += LogUtils.MapToStringMethod(wjjlMap);
            spcyLogService.addLogs(LogConstant.LOGS_SQSX_WJJL, czContent, spcySqsxWjjl.getFpid(), "上传文件", SpcyConstant.LOGS_SYS_TYPE_BC);
        }

        // 删除旧的文件
        if (isDeleteFileId){
            spcySqsxWjjlService.removeById(fileid);
            if (org.apache.commons.lang3.StringUtils.isNotBlank(oldWjjl.getFcflj())) {
                localFileUploadUtils.deleteLocalFileUrl(oldWjjl.getFcflj());
            }
            if (org.apache.commons.lang3.StringUtils.isNotBlank(oldWjjl.getFjdcflj())){
                localFileUploadUtils.deleteLocalFileUrl(oldWjjl.getFjdcflj());
            }
        }
    }

    /**
     * 获取制作中补齐补正通知文件-中心
     * @param sqsxid
     * @return
     */
    public List<SpcySqsxWjjl> getBqbzFileListByFwjlx2(String sqsxid){
        return spcySqsxWjjlService.getTbwdWjjlListByFwjlx2(sqsxid, WjmlConstant.bccltzh, false);
    }

    /**
     * 企业端-获取补齐补正通知文件
     */
    public List<SpcySqsxWjjl> getBztzFileByQy(String sqsxid){
        List<SpcySqsxWjjl> list = spcySqsxWjjlService.getTbWcWjjlListByFwjlx2(sqsxid, WjmlConstant.bccltzh, true);
        if (CollectionUtil.isNotEmpty(list)){
            return CollectionUtil.newArrayList(list.get(0));
        }
        return list;
    }

    /**
     * 自动盖章-补齐补正通知函文件（完成）
     * @param sqsxid
     * @return
     */
    @Async(value = "asyncNormalTask")
    public void verifyAutoGzBqbzFile(String sqsxid){

        List<SpcySqsxWjjl> wjList = spcySqsxWjjlService.getTbWcWjjlListByFwjlx2(sqsxid, WjmlConstant.bccltzh, false);
        this.verifyAutoPdfFileGz(wjList);
    }

    /**
     * 自动盖章-缺陷调整通知书文件（完成）
     * @param sqsxid
     * @return
     */
    @Async(value = "asyncNormalTask")
    public void verifyAutoGzZgtzsFile(String sqsxid){

        List<SpcySqsxWjjl> wjList = spcySqsxWjjlService.getTbWcWjjlListByFwjlx2(sqsxid, WjmlConstant.jcqxtztzs, false);
        this.verifyAutoPdfFileGz(wjList);
    }

    /**
     * 企业撤件通知-文件盖章
     * @param sqsxid
     */
    @Async(value = "asyncNormalTask")
    public void verifyAutoQycjFileGz(String sqsxid){
        List<SpcySqsxWjjl> wjjlList = spcySqsxWjjlService.getTbwdWjjlListByFwjlx2(sqsxid, WjmlConstant.qycjcl, false);
        this.verifyAutoPdfFileGz(wjjlList);
    }

    /**
     * 获取历史补齐补正文件列表
     * @param sqsxid
     * @return
     */
    public List<SpcySqsxWjjl> queryHistoryWjjlList(String sqsxid){
        return spcySqsxWjjlService.getHistoryWjjlList(sqsxid, WjmlConstant.bccltzh, false);
    }

    /**
     * 获取制作中企业撤件通知文件
     * @param sqsxid
     * @return
     */
    public List<SpcySqsxWjjl> getQycjFileListByFwjlx2(String sqsxid){
        return spcySqsxWjjlService.getTbwdWjjlListByFwjlx2(sqsxid, WjmlConstant.qycjcl, false);
    }

    /**
     * 获取制作中整改通知书文件
     * @param sqsxid
     * @return
     */
    public HttpResult fqqxtzFile(String sqsxid){
        List<SpcySqsxWjjl> list = spcySqsxWjjlService.list(new LambdaQueryWrapper<SpcySqsxWjjl>()
                .eq(SpcySqsxWjjl::getFpid, sqsxid)
                .eq(SpcySqsxWjjl::getFwjlx1, WjmlConstant.jcqxtztzs)
                .eq(SpcySqsxWjjl::getFwjlx2, SpcyCommonConstant.SQSX_WJJL_TYPE2_TBWDZ)
                .orderByDesc(SpcySqsxWjjl::getCreateTime));
        if (CollectionUtil.isNotEmpty(list)){
            return HttpResultVo.HttpResultGet(list.get(0));
        }

        return HttpResultVo.HttpResultGet(initJcqxTzs(sqsxid, spcySqsxBaiscService.selectSqsxById(sqsxid), WjmlConstant.jcqxtztzs, "", WjmlConstant.YPSC_JCQXTZTZS_TEMPLATE_NAME));
    }

    /** 获取制作中整改通知书文件-完成 */
    public HttpResult fqqxtzWc(String sqsxid){

        updateZgtzsFileByTbwdz(sqsxid);

        verifyAutoGzZgtzsFile(sqsxid);

        return HttpResult.ok("操作成功");
    }

    /**
     * 更新同步制作中的补齐补正材料为完成状态
     * @param sqsxid
     */
    public void updateZzzBqbzFileByTbwdz(String sqsxid){
        spcySqsxWjjlService.updateWjjlByTbwdz(sqsxid, WjmlConstant.bccltzh);
    }

    /**
     * 更新同步制作中的缺陷调整通知书文件材料为完成状态
     * @param sqsxid
     */
    public void updateZgtzsFileByTbwdz(String sqsxid){
        spcySqsxWjjlService.updateWjjlByTbwdz(sqsxid, WjmlConstant.jcqxtztzs);
    }

    /** 更新-恢复同意选派人员工作状态 */
    @Async(value = "asyncSimpleTask")
    public void updateCyUserGzzt(String sqsxId){
        List<SpcySqsxXpjl> xpList = spcySqsxXpjlService.getTyXpXpjlListNotOrder(sqsxId);
        busService.updateXpryUserGzztInZg(xpList);
    }

    /**
     * 方案文件自动盖章
     * @param sqsxid
     */
    public void verifyAutoFaFileGz(String sqsxid){
        List<SpcySqsxWjjl> wjjlList = spcySqsxWjjlService.list(new LambdaQueryWrapper<SpcySqsxWjjl>()
                .eq(SpcySqsxWjjl::getFwjlx1, WjmlConstant.jcfa)
                .eq(SpcySqsxWjjl::getFpid, sqsxid));
        this.verifyAutoPdfFileGz(wjjlList);
    }

    /**
     * 方案制作提交-相关文件自动生成pdf并盖章
     */
    @Async(value = "asyncNormalTask")
    public void verifyAutoFileGzByFazd(String sqsxid){
        List<String> typeList = CollectionUtil.newArrayList(
                WjmlConstant.jcfa,
                WjmlConstant.xpxcscydh,
                WjmlConstant.qydwjctz,
                WjmlConstant.xpxcgcydh,
                WjmlConstant.jczgclyq);

        List<SpcySqsxWjjl> wjList = spcySqsxWjjlService.findWjjlListByFwjlx1(typeList, sqsxid);
        this.verifyAutoPdfFileGz(wjList);
    }

    /**
     * 移送确认提交-文件盖章
     * @param sqsxid
     */
    public void verifyAutoFileGzByCommons(String sqsxid, List<String> typeList){
        try {
            CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
                List<SpcySqsxWjjl> wjList = spcySqsxWjjlService.findWjjlListByFwjlx1(typeList, sqsxid);
                this.verifyAutoPdfFileGz(wjList);

                return 1;
            }, executor);

            try {
                future.get();
            } catch (InterruptedException e) {
                log.error("[InterruptedException]移送确认提交-文件盖章: {}", e.getMessage());
            } catch (ExecutionException e) {
                log.error("[InterruptedException]移送确认提交-文件盖章: {}", e.getMessage());
            }

        }catch (Exception e){
            log.error("移送确认提交-文件盖章错误：{}", e.getMessage());
        }

    }

    public void verifyAutoFileGzByYsqr(String sqsxid){
        /*List<String> typeList = CollectionUtil.newArrayList(
                WjmlConstant.yshmb,
                WjmlConstant.xcjcbg,
                WjmlConstant.zhpdbgs,
                WjmlConstant.xcjcbl
        );*/
        verifyAutoFileGzByCommon(sqsxid, WjmlConstant.jsspbg, WjmlConstant.zhpdbgs);
    }
    /**
     * 提交-文件盖章
     * @param sqsxid
     */
    public void verifyAutoFileGzByCommon(String sqsxid, String... type){
        try {
            List<String> typeList = CollectionUtil.newArrayList(type);

            verifyAutoFileGzByCommons(sqsxid, typeList);
           /* List<SpcySqsxWjjl> wjList = spcySqsxWjjlService.findWjjlListByFwjlx1(typeList, sqsxid);
            this.verifyAutoPdfFileGz(wjList);*/
        }catch (Exception e){
            log.error("通用提交-文件盖章错误：{}", e.getMessage());
        }

    }

    /**
     * 相关文件自动生成pdf并盖章
     */
    private void verifyAutoPdfFileGz(List<SpcySqsxWjjl> wjjlList){
        try {
            if (CollectionUtils.isNotEmpty(wjjlList)) {
                String ml = "/" + DateConversionUtils.DateToMonthTwo(new Date());
                busService.initLocalTempFileMl(ml);

                for (SpcySqsxWjjl wjjl : wjjlList) {
                    hnCaUtils.sqsxFileToMinioGz(wjjl, ml);
                }
            }
        }catch (Exception e){
            log.error("相关文件自动生成pdf并盖章-异常: {}", e.getMessage());
        }
    }

    /**
     * 验证方案制作文件是否已经盖章
     * */
    public String verifyFaspFileIsGz(String sqsxid){

        List<String> typeList = CollectionUtil.newArrayList(
                WjmlConstant.jcfa,
                WjmlConstant.xpxcscydh,
                WjmlConstant.qydwjctz,
                WjmlConstant.xpxcgcydh,
                WjmlConstant.jczgclyq);
        List<SpcySqsxWjjl> wjList = spcySqsxWjjlService.findWjjlListByFwjlx1(typeList, sqsxid);

        String errorMsg = "";
        for (SpcySqsxWjjl wjjl : wjList){
            if (StringUtils.isNotBlank(wjjl.getFwjlx4())
                    && wjjl.getFwjlx4().equals(SpcyCommonConstant.SQSX_WJJL_TYPE4_SDSC)) {
                continue;
            }

            if (StringUtils.isBlank(wjjl.getFwjlx3()) || !wjjl.getFwjlx3().equals(SpcyCommonConstant.SQSX_WJJL_TYPE3_YWC)){
                errorMsg += wjjl.getFwjlx1() + "[材料没有盖章]；";
            }
        }

        return errorMsg;
    }

    /**
     * 补充资料通知函-药品生产
     * @param sqsxid
     */
    public void initBqbzTzWjmbInYpsc(String sqsxid, String spyj){
        String type = WjmlConstant.bccltzh;
        String relativePath = WjmlConstant.YPSC_BQBZCL_TEMPLATE_NAME;
        String wjxsmc = "";
        SpcySqsxBasic sqsx = spcySqsxBaiscService.selectSqsxById(sqsxid);
        if (sqsx == null){
            throw new BusinessException("没有相匹配的数据");
        }
        wjxsmc = sqsx.getFqymc() + "补充材料通知";
        this.initSyncWjmbCommon(sqsxid, sqsx, spyj, relativePath, type, wjxsmc);
    }

    /**
     * 企业撤件通知材料-药品生产
     * @param sqsxid
     */
    public void initQycjWjmbInYpsc(String sqsxid, String opinion){
        String type = WjmlConstant.qycjcl;
        String relativePath = WjmlConstant.YPSC_QYCJ_TEMPLATE_NAME;
        String wjxsmc = "";
        SpcySqsxBasic sqsx = spcySqsxBaiscService.selectSqsxById(sqsxid);
        if (sqsx == null){
            throw new BusinessException("没有相匹配的数据");
        }
        wjxsmc = sqsx.getFqymc() + "撤件的函";
        this.initSyncWjmbCommon(sqsxid, sqsx, opinion, relativePath, type, wjxsmc);
    }

    /** 上传缺陷调整通知书 */
    public void initUploadZgtzs(MultipartFile[] uploadFile, String sqsxid, String type){

        // 是否存在该类型的文件
        List<SpcySqsxWjjl> oldWjllist = spcySqsxWjjlService.getTbwdWjjlListByFwjlx2(sqsxid, type, false);
        // 不存在，新增
        if (CollectionUtils.isNotEmpty(oldWjllist)) {
            for (SpcySqsxWjjl oldWj : oldWjllist) {
                /*if (StringUtils.isNotBlank(oldWj.getFwjlx3())
                        && oldWj.getFwjlx3().equals(SpcyCommonConstant.SQSX_WJJL_TYPE3_ZZZ)){*/
                    if (StringUtils.isNotBlank(oldWj.getFcflj())) {
                        localFileUploadUtils.deleteLocalFileUrl(oldWj.getFcflj());
                    }
                    if (StringUtils.isNotBlank(oldWj.getFjdcflj())) {
                        localFileUploadUtils.deleteLocalFileUrl(oldWj.getFjdcflj());
                    }
                    spcySqsxWjjlService.removeById(oldWj.getId());
                /*}else {
                    return;
                }*/
            }
        }

        uploadCommonFile(uploadFile, sqsxid, type, SpcyCommonConstant.SQSX_WJJL_TYPE2_TBWDZ, "", false);
    }

    /** 通用同步文档 */
    public void initSyncWjmbCommon(String sqsxid, SpcySqsxBasic sqsx, String opinion, String relativePath, String type, String wjxsmc){

        // 是否存在该类型的文件
        List<SpcySqsxWjjl> oldWjllist = spcySqsxWjjlService.getTbwdWjjlListByFwjlx2(sqsxid, type, false);
        // 不存在，新增
        if (CollectionUtils.isNotEmpty(oldWjllist)) {
            for (SpcySqsxWjjl oldWj : oldWjllist) {
                /*if (StringUtils.isNotBlank(oldWj.getFwjlx3())
                        && oldWj.getFwjlx3().equals(SpcyCommonConstant.SQSX_WJJL_TYPE3_ZZZ)){*/
                    if (StringUtils.isNotBlank(oldWj.getFcflj())) {
                        localFileUploadUtils.deleteLocalFileUrl(oldWj.getFcflj());
                    }
                    if (StringUtils.isNotBlank(oldWj.getFjdcflj())) {
                        localFileUploadUtils.deleteLocalFileUrl(oldWj.getFjdcflj());
                    }
                    spcySqsxWjjlService.removeById(oldWj.getId());
                /*}else {
                    return;
                }*/
            }
        }

        String fywflcode = sqsx.getFywflcode();
        String wjmbUrl = "";
        SqsxWjmbVo wjmbBySqsxId = busService.getWjmbBySqsxId("", sqsxid, sqsx, fywflcode, type);
        if (StringUtils.isBlank(wjmbBySqsxId.getErrorMsg())){
            wjmbUrl = wjmbBySqsxId.getWjmbUrl();
        }else {
            // 模板路径
            wjmbUrl = businessConstant.UPLOAD_FILE_ROOT + "/" + relativePath;
        }

        String wjlx = Util.getWjHz(wjmbUrl); // 获取文件路径的 文件类型
        String formatType = BusinessConstant.getWordFormatType(wjlx); // word替换格式

        Map<String,String> map = new HashMap<>();
        SpcySqsxWjjl newWjjl = null;

        String sjmc = ""; // 文件虚假名称
        String wjccmc = ""; // 文件存储名称

        String newDir = "/" + DateConversionUtils.DateToMonthTwo(new Date());
        busService.initLocalTempFileMl(newDir);

        String cflj = ""; // 文件存放路径

        SpcySqsxWjjl wjjl = new SpcySqsxWjjl();
        wjjl.setFpid(sqsxid);
        wjjl.setFwjlx(wjlx);
        wjjl.setFwjlx1(type);
        wjjl.setFwjlx2(SpcyCommonConstant.SQSX_WJJL_TYPE2_TBWDZ);
        wjjl.setFwjlx3(SpcyCommonConstant.SQSX_WJJL_TYPE3_ZZZ);

        String fqymc = sqsx.getFqymc();

        if (StringUtils.isBlank(wjxsmc)){
            wjxsmc = type + "-" + fqymc; // 文件显示名称
        }

        sjmc = GetUuIdUtils.NotReplaceUuId();
        wjccmc = sjmc + wjlx;
        cflj = newDir + "/" + wjccmc;
        newWjjl = new SpcySqsxWjjl();
        BeanUtil.copyProperties(wjjl, newWjjl);

        map = busService.getObjectMap(sqsxid,"", false, false); // 获取替换相关内容
        map.put("${data.mbyj}", opinion);
        String wordText = busService.genSqsxWj(cflj, wjlx, wjmbUrl, "", formatType, map);

        newWjjl.setId(GetUuIdUtils.ReplaceUuId());
        newWjjl.setFywflcode(fywflcode);
        newWjjl.setFwjxsmc(wjxsmc);
        newWjjl.setFwjccmc(wjccmc);
        newWjjl.setFcflj(cflj);
        newWjjl.setFwjnr(wordText);
        newWjjl.setFbusid(sqsx.getFqyid());
        newWjjl.setFbusmc(wjxsmc);
        spcySqsxWjjlService.save(newWjjl);
    }


    /**
     * 查询综合评定报告书-文件记录
     * @param sqsxid 申请事项id
     */
    public List<SpcySqsxWjjl> getZhpdbgFile(String sqsxid){

        return spcySqsxWjjlService.getWjjlListByPidAndType(sqsxid, WjmlConstant.zhpdbgs, true);

    }

    /** 异步初始化现场检查笔录 */
    @Async(value = "asyncNormalTask")
    public void asyncInitXcjcblFile(String sqsxid){
        busService.initXcjcbl(sqsxid, WjmlConstant.xcjcbl, ""); // 初始化文件记录
    }

    /**
     * 方案制定-完成抽选人员-生成通知函
     * */
    public void wccxrySctzh(String sqsxid){

        // 是否存在待确认
        /*List<SpcySqsxXpjl> dqrXpXpjlList = spcySqsxXpjlService.getDqrXpXpjlList(sqsxid, null, false);
        if (CollectionUtils.isNotEmpty(dqrXpXpjlList)){
            throw new BusinessException("操作失败！还存在待确认选人员！");
        }*/

        busService.initJcfa(sqsxid, WjmlConstant.jcfa, ""); // 检查方案

        busService.initXpxcscydh(sqsxid, WjmlConstant.xpxcscydh, ""); // 初始化文件记录
        // 删除观察员函
        busService.deleteXgInitScFile("", sqsxid, WjmlConstant.xpxcgcydh);
        busService.initSqsxGcy(sqsxid);// 初始化观察员
        busService.initXpxcgcydh(sqsxid, WjmlConstant.xpxcgcydh, ""); // 初始化文件记录

        busService.initQydwjctz(sqsxid, WjmlConstant.qydwjctz, ""); // 企业单位检查通知
        busService.initJczgclyq(sqsxid, WjmlConstant.jczgclyq, ""); // 检查整改材料要求

    }

    /**
     * 根据现场检查会议签到人员-生成相关的事项文件记录
     */
    @Async(value = "asyncNormalTask")
    public void initSqsxWjjlByHy(SpcySqsxHymx userHymx, String sqsxid){
        String ywflCode = spcySqsxBaiscService.getYwflCodeBySqsxId(sqsxid);

        this.genWlyctsmSqsxWjjlByHy(userHymx, sqsxid, ywflCode);
        this.genJcycnsSqsxWjjlByHy(userHymx, sqsxid, ywflCode);
    }

    /**
     * 初始化-无利益冲突声明
     * @return 临时绝对路径
     */
    private String initWlyctsmSqsxWjjlByHy(SpcySqsxHymx userHymx, String ywflCode){

        // 获取签名地址
        SpcySqsxWjjl qm = spcySqsxWjjlService.downMyUserQm(userHymx.getFuserid(), null);
        if (qm == null){
            return null;
        }

        File file = null;
        if (localFileUploadUtils.isEnableMinioQmFile()) {
            InputStream inputStream = spcyMinioUtils.getObject(LocalFileUploadUtils.getUserQmRelaviteUrl(qm.getFcflj()));
            if (inputStream == null) {
                return null;
            }

            file = localFileUploadUtils.asFile(inputStream, Util.getWjHz(qm.getFcflj()));
        }else {
            file = new File(localFileUploadUtils.getUserQmAbsUrl(qm.getFcflj()));
        }

        HashMap<String, Object> templateField = new HashMap<>();

        templateField.put("nowdate", DateConversionUtils.DateToStringNew(userHymx.getFhyqdrq()));

        String wlysmsz = "□";
        String wlylyct = "□";
        String wlysfczlygx = "□";
        if (StringUtils.isNotBlank(userHymx.getWlysmsz()) && (userHymx.getWlysmsz().equals("true") || userHymx.getWlysmsz().equals("是"))){
            wlysmsz = "√";
        }
        if (StringUtils.isNotBlank(userHymx.getWlylyct()) && (userHymx.getWlylyct().equals("true") || userHymx.getWlylyct().equals("是"))){
            wlylyct = "√";
        }
        if (StringUtils.isNotBlank(userHymx.getWlysfczlygx()) && (userHymx.getWlysfczlygx().equals("true") || userHymx.getWlysfczlygx().equals("是"))){
            wlysfczlygx = "√";
        }

        templateField.put("wlysmsz", wlysmsz);
        templateField.put("wlylyct", wlylyct);
        templateField.put("wlysfczlygx", wlysfczlygx);
        templateField.put("wlyczlygx", Optional.ofNullable(userHymx.getWlyczlygx()).orElseGet(()->""));

        try {
            templateField.put("qm", Pictures.ofStream(new FileInputStream(file.getAbsoluteFile()), PictureType.JPEG)
                    .size(80, 40).create());
        } catch (FileNotFoundException e) {
            return null;
        }

        String orgUrl = businessConstant.UPLOAD_FILE_ROOT + "/" + WjmlConstant.getWlyctsmTemplateUrl(ywflCode);
        String destWordUrl = localFileUploadUtils.getTempFileRootUrl() + "/";
        destWordUrl += GetUuIdUtils.NotReplaceUuId() + Util.getWjHz(orgUrl);
        boolean flag = WordDocxReplaceUtils.docxReplaceFlag(orgUrl, destWordUrl, templateField);

        if (flag) {
            return destWordUrl;
        }

        return null;
    }

    /**
     * 构建-无利益冲突声明-文件记录
     */
    private void genWlyctsmSqsxWjjlByHy(SpcySqsxHymx userHymx, String sqsxid, String ywflCode){
        if (StringUtils.isBlank(sqsxid)){
            return;
        }

        // 获取初始化文件
        String destWordUrl = "";
        try {
            destWordUrl = this.initWlyctsmSqsxWjjlByHy(userHymx, ywflCode);
        }catch (Exception e){
            log.error("构建无利益冲突声明模板错误：", e.getMessage());
        }
        if (StringUtils.isBlank(destWordUrl)){
            return;
        }

        // pdf保存路径
        String wjccmc = GetUuIdUtils.NotReplaceUuId() + ".pdf";
        String destPdfUrl = localFileUploadUtils.getTempFileRootUrl() + "/" + wjccmc;

        // 生成pdf
        WordPdfUtils.wordToPdf(destWordUrl, destPdfUrl);
        String cflj = "/" + DateConversionUtils.DateToMonthTwo(new Date()) + "/" + wjccmc;

        // minio文件上传
        boolean flag = busService.uploadMinioFileWjjl(cflj, destPdfUrl);
        if (flag) {
            this.initSqsxWjjl(sqsxid, WjmlConstant.wlyctsm, ".pdf", WjmlConstant.wlyctsm + "-" + userHymx.getFxm(), wjccmc, cflj);
        }
    }

    /**
     * 下载-无利益冲突声明-文件
     */
    public void downWlyctsmSqsxWjjlByHy(SpcySqsxHymx userHymx, HttpServletResponse response) throws IOException {
        // 获取初始化文件
        String destWordUrl = this.initWlyctsmSqsxWjjlByHy(userHymx, "");
        if (StringUtils.isBlank(destWordUrl)){
            response.setContentType("text/html");
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.println("下载失败，无相关文件模板！");
            writer.close(); // 不要忘记关闭PrintWriter
            return;
        }

        localFileUploadUtils.ejzLocalFileByZdyFile(new File(destWordUrl), response);
    }

    /**
     * 初始化-现场检查检查员承诺书-文件记录
     *  @return 临时绝对路径
     */
    private String initJcycnsSqsxWjjlByHy(SpcySqsxHymx userHymx, String ywflCode){
        // 获取签名地址
        SpcySqsxWjjl qm = spcySqsxWjjlService.downMyUserQm(userHymx.getFuserid(), null);
        if (qm == null){
            return null;
        }

        File file = null;
        if (localFileUploadUtils.isEnableMinioQmFile()) {
            InputStream inputStream = spcyMinioUtils.getObject(LocalFileUploadUtils.getUserQmRelaviteUrl(qm.getFcflj()));
            if (inputStream == null) {
                return null;
            }

             file = localFileUploadUtils.asFile(inputStream, Util.getWjHz(qm.getFcflj()));
        }else {
            file = new File(localFileUploadUtils.getUserQmAbsUrl(qm.getFcflj()));
        }

        HashMap<String, Object> templateField = new HashMap<>();
        templateField.put("nowdate", DateConversionUtils.DateToStringNew(userHymx.getFhyqdrq()));
        try {
            // 150 80
            templateField.put("qm", Pictures.ofStream(new FileInputStream(file.getAbsoluteFile()), PictureType.JPEG)
                    .size(80, 40).create());
        } catch (FileNotFoundException e) {
            return null;
        }

        String orgUrl = businessConstant.UPLOAD_FILE_ROOT + "/" + WjmlConstant.getjcycnsTemplateUrl(ywflCode);
        String destWordUrl = localFileUploadUtils.getTempFileRootUrl() + "/";
        destWordUrl += GetUuIdUtils.NotReplaceUuId() + Util.getWjHz(orgUrl);
        boolean flag = WordDocxReplaceUtils.docxReplaceFlag(orgUrl, destWordUrl, templateField);

        if (flag){
            return destWordUrl;
        }

        return null;
    }

    /**
     * 构建-现场检查检查员承诺书-文件记录
     */
    private void genJcycnsSqsxWjjlByHy(SpcySqsxHymx userHymx, String sqsxid, String ywflCode){
        if (StringUtils.isBlank(sqsxid)){
            return;
        }

        // 获取初始化文件
        String destWordUrl = "";
        try {
            destWordUrl = this.initJcycnsSqsxWjjlByHy(userHymx, ywflCode);
        }catch (Exception e){
            log.error("构建现场检查检查员承诺书模板错误：", e.getMessage());
        }
        if (StringUtils.isBlank(destWordUrl)){
            return;
        }

        // pdf保存路径
        String wjccmc = GetUuIdUtils.NotReplaceUuId() + ".pdf";
        String destPdfUrl = localFileUploadUtils.getTempFileRootUrl() + "/" + wjccmc;

        // 生成pdf
        WordPdfUtils.wordToPdf(destWordUrl, destPdfUrl);

        String cflj = "/" + DateConversionUtils.DateToMonthTwo(new Date()) + "/" + wjccmc;

        // minio文件上传
        boolean flag = busService.uploadMinioFileWjjl(cflj, destPdfUrl);
        if (flag) {
            this.initSqsxWjjl(sqsxid, WjmlConstant.xcjcjcycns, ".pdf", WjmlConstant.xcjcjcycns + "-" + userHymx.getFxm(), wjccmc, cflj);
        }
    }

    /**
     * 下载-现场检查检查员承诺书-文件
     */
    public void downJcycnsSqsxWjjlByHy(SpcySqsxHymx userHymx, HttpServletResponse response) throws IOException {
        // 获取初始化文件
        String destWordUrl = this.initJcycnsSqsxWjjlByHy(userHymx, "");
        if (StringUtils.isBlank(destWordUrl)){
            response.setContentType("text/html");
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.println("下载失败，无相关文件模板！");
            writer.close(); // 不要忘记关闭PrintWriter
            return;
        }

        localFileUploadUtils.ejzLocalFileByZdyFile(new File(destWordUrl), response);
    }

    /** 初始化-现场检查会议签到表-根据现场检查会议相关信息
     * @param mchyMap 末次会议相关 jcyList/gcyList/qyList/hy
     * @param schyMap 首次会议相关
     * @param hylxFlag 0: 合并； 1：首次会议; 2: 末次会议
     * */
    private String initXcjchyQdbByHyxx(String sqsxid, Map schyMap, Map mchyMap, int hylxFlag) {

        HashMap<String, Object> parMap = new HashMap<>();
        ConfigureBuilder builder = Configure.builder();

        SpcySqsxBasic sqsx = spcySqsxBaiscService.selectSqsxInfoById(sqsxid);

        /** 事项信息 */
        String fqymc = "";
        String fqyzszcdz = "";
        String fcyjcfw = "";
        String fjclx = "";
        String fywflcode = "";

        if (sqsx != null) {
            fqymc = sqsx.getFqymc();
            fqyzszcdz = Optional.ofNullable(sqsx.getFqyzszcdz()).orElseGet(()->"");
            fcyjcfw = Optional.ofNullable(sqsx.getFcyjcfw()).orElseGet(()->"");
            fjclx = sqsx.getFjclx();
            fywflcode = sqsx.getFywflcode();
        }

        parMap.put("fqymc", fqymc);
        parMap.put("fqyzszcdz", fqyzszcdz);
        parMap.put("fcyjcfw", fcyjcfw);
        parMap.put("fjclx", fjclx);


        /** 首次会议 */
        if (hylxFlag == 1 || hylxFlag == 0) {
            String fhysj1 = "";
            String fhydd1 = "";
            List<Map<String, PictureRenderData>> pictureList_jcy = new ArrayList<>();
            List<Map<String, PictureRenderData>> pictureList_gcy = new ArrayList<>();
            List<SqsxHyXcjcqdbVo> qyDataList = new ArrayList<>();

            try {
                if (schyMap != null) {
                    SpcySqsxHyzt hy = (SpcySqsxHyzt) schyMap.get("hy");
                    List<SpcySqsxHymx> jcyList = (List<SpcySqsxHymx>) schyMap.get("jcyList");
                    List<SpcySqsxHymx> gcyList = (List<SpcySqsxHymx>) schyMap.get("gcyList");
                    List<SpcySqsxHymx> qyList = (List<SpcySqsxHymx>) schyMap.get("qyList");

                    fhysj1 = DateConversionUtils.DateToStringNew(hy.getFhysj());
                    fhydd1 = hy.getFhydd();

                    for (SpcySqsxHymx bean : jcyList) {
                        if (StringUtils.isNotBlank(bean.getFqmfj())) {
                            String fileUrl = this.getMinioFileStreamTest(bean.getFqmfj().split("\\?id=")[1]);
                            if (StringUtils.isNotBlank(fileUrl)) {
                                Map<String, PictureRenderData> picture = new HashMap<>();
                                try {
                                    picture.put("picture", Pictures.ofStream(new FileInputStream(fileUrl), PictureType.JPEG)
                                            .size(50, 30).create());
                                } catch (FileNotFoundException e) {
                                    e.printStackTrace();
                                }
                                pictureList_jcy.add(picture);
                            }
                        }
                    }

                    for (SpcySqsxHymx bean : gcyList) {
                        if (StringUtils.isNotBlank(bean.getFqmfj())) {
                            String fileUrl = this.getMinioFileStreamTest(bean.getFqmfj().split("\\?id=")[1]);
                            if (StringUtils.isNotBlank(fileUrl)) {
                                Map<String, PictureRenderData> picture = new HashMap<>();
                                try {
                                    picture.put("picture", Pictures.ofStream(new FileInputStream(fileUrl), PictureType.JPEG)
                                            .size(50, 30).create());
                                } catch (FileNotFoundException e) {
                                    e.printStackTrace();
                                }
                                pictureList_gcy.add(picture);
                            }
                        }
                    }

                    int dataLength = qyList.size();
                    for (int index = 0; index < qyList.size(); index++) {

                        boolean flag = false;
                        SqsxHyXcjcqdbVo bean = new SqsxHyXcjcqdbVo();
                        int dataIndex = index;
                        if (index > 0) {
                            dataIndex = index + 1;
                        }

                        if (dataIndex < dataLength) {
                            if (StringUtils.isNotBlank(qyList.get(dataIndex).getFqmfj())) {
                                String fileUrl = this.getMinioFileStreamTest(qyList.get(dataIndex).getFqmfj().split("\\?id=")[1]);
                                if (StringUtils.isNotBlank(fileUrl)) {
                                    PictureRenderData pictureRenderData = null;
                                    try {
                                        pictureRenderData = Pictures.ofStream(new FileInputStream(fileUrl), PictureType.JPEG)
                                                .size(80, 40).create();
                                    } catch (FileNotFoundException e) {
                                        e.printStackTrace();
                                    }
                                    bean.setFqmfj(pictureRenderData);
                                }
                            }

                            bean.setFbm(qyList.get(dataIndex).getFbm());
//                            bean.setFzw(qyList.get(dataIndex).getFzw());

                            flag = true;
                        }

                        if (dataIndex + 1 < dataLength) {
                            if (StringUtils.isNotBlank(qyList.get(dataIndex + 1).getFqmfj())) {
                                String fileUrl = this.getMinioFileStreamTest(qyList.get(dataIndex + 1).getFqmfj().split("\\?id=")[1]);
                                if (StringUtils.isNotBlank(fileUrl)) {
                                    PictureRenderData pictureRenderData = null;
                                    try {
                                        pictureRenderData = Pictures.ofStream(new FileInputStream(fileUrl), PictureType.JPEG)
                                                .size(80, 40).create();
                                    } catch (FileNotFoundException e) {
                                        e.printStackTrace();
                                    }
                                    bean.setFqmfj2(pictureRenderData);
                                }
                            }

                            bean.setFbm2(qyList.get(dataIndex + 1).getFbm());
//                            bean.setFzw2(qyList.get(dataIndex + 1).getFzw());
                            flag = true;
                        }

                        if (flag) {
                            qyDataList.add(bean);
                        }
                    }
                }
            } catch (Exception e) {
                log.error("首次会议-会议相关信息初始化出错：{}", e.getMessage());
            }

            parMap.put("fhysj1", fhysj1);
            parMap.put("fhydd1", fhydd1);
            parMap.put("jcyList1", pictureList_jcy);
            parMap.put("gcyList1", pictureList_gcy);
            parMap.put("list1", qyDataList);

        }

        /** 末次会议 */
        if (hylxFlag == 2 || hylxFlag == 0) {
            String fhysj2 = "";
            String fhydd2 = "";
            List<Map<String, PictureRenderData>> pictureList_jcy2 = new ArrayList<>();
            List<Map<String, PictureRenderData>> pictureList_gcy2 = new ArrayList<>();
            List<SqsxHyXcjcqdbVo> qyDataList2 = new ArrayList<>();

            try {
                if (mchyMap != null) {
                    SpcySqsxHyzt hy = (SpcySqsxHyzt) mchyMap.get("hy");
                    List<SpcySqsxHymx> jcyList = (List<SpcySqsxHymx>) mchyMap.get("jcyList");
                    List<SpcySqsxHymx> gcyList = (List<SpcySqsxHymx>) mchyMap.get("gcyList");
                    List<SpcySqsxHymx> qyList = (List<SpcySqsxHymx>) mchyMap.get("qyList");

                    /** 会议信息 */
                    fhysj2 = DateConversionUtils.DateToStringNew(hy.getFhysj());
                    fhydd2 = hy.getFhydd();

                    /** 检查员相关信息 */
                    for (SpcySqsxHymx bean : jcyList) {
                        if (StringUtils.isNotBlank(bean.getFqmfj())) {
                            String fileUrl = this.getMinioFileStreamTest(bean.getFqmfj().split("\\?id=")[1]);
                            if (StringUtils.isNotBlank(fileUrl)) {
                                Map<String, PictureRenderData> picture = new HashMap<>();
                                try {
                                    picture.put("picture", Pictures.ofStream(new FileInputStream(fileUrl), PictureType.JPEG)
                                            .size(50, 30).create());
                                } catch (FileNotFoundException e) {
                                    e.printStackTrace();
                                }
                                pictureList_jcy2.add(picture);
                            }
                        }
                    }


                    /** 观察员相关信息 */
                    for (SpcySqsxHymx bean : gcyList) {
                        if (StringUtils.isNotBlank(bean.getFqmfj())) {
                            String fileUrl = this.getMinioFileStreamTest(bean.getFqmfj().split("\\?id=")[1]);
                            if (StringUtils.isNotBlank(fileUrl)) {
                                Map<String, PictureRenderData> picture = new HashMap<>();
                                try {
                                    picture.put("picture", Pictures.ofStream(new FileInputStream(fileUrl), PictureType.JPEG)
                                            .size(50, 30).create());
                                } catch (FileNotFoundException e) {
                                    e.printStackTrace();
                                }
                                pictureList_gcy2.add(picture);
                            }
                        }
                    }

                    /** 企业签名相关信息 */
                    int dataLength = qyList.size();
                    for (int index = 0; index < qyList.size(); index++) {

                        boolean flag = false;
                        SqsxHyXcjcqdbVo bean = new SqsxHyXcjcqdbVo();
                        int dataIndex = index;
                        if (index > 0) {
                            dataIndex = index + 1;
                        }

                        if (dataIndex < dataLength) {
                            if (StringUtils.isNotBlank(qyList.get(dataIndex).getFqmfj())) {
                                String fileUrl = this.getMinioFileStreamTest(qyList.get(dataIndex).getFqmfj().split("\\?id=")[1]);
                                if (StringUtils.isNotBlank(fileUrl)) {
                                    PictureRenderData pictureRenderData = null;
                                    try {
                                        pictureRenderData = Pictures.ofStream(new FileInputStream(fileUrl), PictureType.JPEG)
                                                .size(80, 40).create();
                                    } catch (FileNotFoundException e) {
                                        e.printStackTrace();
                                    }
                                    bean.setFqmfj(pictureRenderData);
                                }
                            }

                            bean.setFbm(qyList.get(dataIndex).getFbm());
//                            bean.setFzw(qyList.get(dataIndex).getFzw());

                            flag = true;
                        }

                        if (dataIndex + 1 < dataLength) {
                            if (StringUtils.isNotBlank(qyList.get(dataIndex + 1).getFqmfj())) {
                                String fileUrl = this.getMinioFileStreamTest(qyList.get(dataIndex + 1).getFqmfj().split("\\?id=")[1]);
                                if (StringUtils.isNotBlank(fileUrl)) {
                                    PictureRenderData pictureRenderData = null;
                                    try {
                                        pictureRenderData = Pictures.ofStream(new FileInputStream(fileUrl), PictureType.JPEG)
                                                .size(80, 40).create();
                                    } catch (FileNotFoundException e) {
                                        e.printStackTrace();
                                    }
                                    bean.setFqmfj2(pictureRenderData);
                                }
                            }

                            bean.setFbm2(qyList.get(dataIndex + 1).getFbm());
//                            bean.setFzw2(qyList.get(dataIndex + 1).getFzw());
                            flag = true;
                        }

                        if (flag) {
                            qyDataList2.add(bean);
                        }
                    }

                }
            } catch (Exception e) {
                log.error("末次会议-会议相关信息初始化出错：{}", e.getMessage());
            }

            parMap.put("fhysj2", fhysj2);
            parMap.put("fhydd2", fhydd2);
            parMap.put("jcyList2", pictureList_jcy2);
            parMap.put("gcyList2", pictureList_gcy2);
            parMap.put("list2", qyDataList2);
        }

        String orgUrl = "";
        HackLoopTableRenderPolicy hackLoopTableRenderPolicy = new HackLoopTableRenderPolicy();
        if (hylxFlag == 1) {
            builder.bind("list1", hackLoopTableRenderPolicy);

            orgUrl = businessConstant.UPLOAD_FILE_ROOT + "/" + WjmlConstant.getXcjcqdbByFirstTemplateUrl(fywflcode);
        }
        else if (hylxFlag == 2) {
            builder.bind("list2", hackLoopTableRenderPolicy);

            orgUrl = businessConstant.UPLOAD_FILE_ROOT + "/" + WjmlConstant.getXcjcqdbByEndTemplateUrl(fywflcode);

        }else if (hylxFlag == 0) {
            builder.bind("list1", hackLoopTableRenderPolicy);
            builder.bind("list2", hackLoopTableRenderPolicy);
            orgUrl = businessConstant.UPLOAD_FILE_ROOT + "/" + WjmlConstant.getXcjcqdbTemplateUrl(fywflcode);
        }

        String destWordUrl = localFileUploadUtils.getTempFileRootUrl() + "/";
        destWordUrl += GetUuIdUtils.NotReplaceUuId() + Util.getWjHz(orgUrl);
        WordDocxReplaceUtils.docxConfigureReplace(orgUrl, destWordUrl, builder.useSpringEL().build(), parMap);

        return destWordUrl;
    }

    /**
     * 初始化-现场检查会议签到表-html转换文件-绑定申请事项
     * @param hylxFlag 0: 合并； 1：首次会议; 2: 末次会议
     * */
    public Result genXcjchyqdbHtmlConvertFile(String sqsxid, Map schyMap, Map mchyMap, int hylxFlag){

        String destWordUrl = "";
        try {
            destWordUrl = this.initXcjchyQdbByHyxx(sqsxid, schyMap, mchyMap, hylxFlag);
        }catch (Exception e){
            log.error("初始化-现场检查会议签到表-根据现场检查会议相关信息出错！{}", e.getMessage());
            return Result.error("操作失败："+e.getMessage());
        }

        if (StringUtils.isBlank(destWordUrl)){
            return Result.error("操作失败，文件模板错误！");
        }

        // pdf保存路径
        String wjccmc = GetUuIdUtils.NotReplaceUuId() + ".pdf";
        String destPdfUrl = localFileUploadUtils.getTempFileRootUrl() + "/" + wjccmc;

        // 生成pdf
        WordPdfUtils.wordToPdf(destWordUrl, destPdfUrl);

        String cflj = "/" + DateConversionUtils.DateToMonthTwo(new Date()) + "/" + wjccmc;

        // minio文件上传
        boolean flag = busService.uploadMinioFileWjjl(cflj, destPdfUrl);
        if (flag) {

            String wjxsmc = WjmlConstant.xcjchyqdb;
            if (hylxFlag == 1){
                wjxsmc += "-"+ SqsxHyConstant.HYLX_SCHY;

            }else if (hylxFlag == 2){
                wjxsmc += "-"+ SqsxHyConstant.HYLX_MCHY;
            }else if (hylxFlag == 0){
                wjxsmc += "-"+ SqsxHyConstant.HYLX_SCHY+"和"+SqsxHyConstant.HYLX_MCHY;
            }

            this.initSqsxWjjl(sqsxid, WjmlConstant.xcjchyqdb, ".pdf", wjxsmc, wjccmc, cflj);
        }else {
            return Result.error("文件上传错误！");
        }

        return Result.ok();
    }

    /** 初始化-现场检查会议签到表-html转换文件-下载 */
    public void downXcjchyqdbHtmlConvertFile(String sqsxid, Map schyMap, Map mchyMap, int hylxFlag, HttpServletResponse response){

        String destWordUrl = "";
        try {
            destWordUrl = this.initXcjchyQdbByHyxx(sqsxid, schyMap, mchyMap, hylxFlag);
        }catch (Exception e){
            log.error("初始化-现场检查会议签到表-根据现场检查会议相关信息出错！{}", e.getMessage());
        }

        if (StringUtils.isNotBlank(destWordUrl)) {
            localFileUploadUtils.ejzLocalFileByZdyFile(new File(destWordUrl), response);
        }
    }

    /**
     * 现场检查报告-相关签名-根据现场检查会议
     * */
    public HashMap<String, Object> initXcjcbgByHqxx(String sqsxid, Map schyMap){
        HashMap<String, Object> parMap = new HashMap<>();

        /** 中心人员 */
        PictureRenderData pictureRenderDataZxry = null;

        /** 组长 */
        PictureRenderData pictureRenderDataZz = null;

        /** 企业负责人 */
        PictureRenderData pictureRenderDataQyFzr = null;

        /** 组员 */
        List<Map<String, PictureRenderData>> pictureList__zy = new ArrayList<>();

        /** 检查组 */
        List<Map<String, PictureRenderData>> pictureList_jcy = new ArrayList<>();

        /** 观察员 */
        List<Map<String, PictureRenderData>> pictureList_gcy = new ArrayList<>();

        int width = 80;
        int height = 40;
        try {
            /** 主办人 */
            SqsxZbrVo zbrVo = spcySqsxBaiscService.selectFzbrById(sqsxid);
            if (zbrVo != null && StringUtils.isNotBlank(zbrVo.getFzbr())){
                String id = StringPatternUtils.getStringsByIds(zbrVo.getFzbr())[0];
                String fileUrl = this.getMinioFileStreamTest("", id);
                if (StringUtils.isNotBlank(fileUrl)){
                    pictureRenderDataZxry = Pictures.ofStream(new FileInputStream(fileUrl), PictureType.JPEG)
                            .size(width, height).create();
                }
            }

            if (schyMap != null){
                List<SpcySqsxHymx> jcyList = (List<SpcySqsxHymx>) schyMap.get("jcyList");
                List<SpcySqsxHymx> gcyList = (List<SpcySqsxHymx>) schyMap.get("gcyList");
                List<SpcySqsxHymx> qyList = (List<SpcySqsxHymx>) schyMap.get("qyList");


                for (SpcySqsxHymx bean : jcyList){

                    if (StringUtils.isNotBlank(bean.getFqmfj())){
                        String fileUrl = this.getMinioFileStreamTest(bean.getFqmfj().split("\\?id=")[1]);
                        if (StringUtils.isNotBlank(fileUrl)) {

                            if (StringUtils.isNotBlank(bean.getFjcsf())) {
                                if (bean.getFjcsf().equals("组长")) {
                                    if (pictureRenderDataZz == null) {
                                        pictureRenderDataZz = Pictures.ofStream(new FileInputStream(fileUrl), PictureType.JPEG)
                                                .size(width, height).create();
                                    }
                                }else if (bean.getFjcsf().equals("组员")){
                                    Map<String, PictureRenderData> picture = new HashMap<>();
                                    try {
                                        picture.put("picture", Pictures.ofStream(new FileInputStream(fileUrl), PictureType.JPEG)
                                                .size(width, height).create());
                                    } catch (FileNotFoundException e) {
                                        e.printStackTrace();
                                    }
                                    pictureList__zy.add(picture);
                                }
                            }

                            Map<String, PictureRenderData> picture = new HashMap<>();
                            try {
                                picture.put("picture", Pictures.ofStream(new FileInputStream(fileUrl), PictureType.JPEG)
                                        .size(width, height).create());
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }
                            pictureList_jcy.add(picture);
                        }
                    }
                }

                for (SpcySqsxHymx bean : gcyList){
                    if (StringUtils.isNotBlank(bean.getFqmfj())){
                        String fileUrl = this.getMinioFileStreamTest(bean.getFqmfj().split("\\?id=")[1]);
                        if (StringUtils.isNotBlank(fileUrl)) {
                            Map<String, PictureRenderData> picture = new HashMap<>();
                            try {
                                picture.put("picture", Pictures.ofStream(new FileInputStream(fileUrl), PictureType.JPEG)
                                        .size(width, height).create());
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }
                            pictureList_gcy.add(picture);
                        }
                    }
                }

                if (CollectionUtil.isNotEmpty(qyList)){
                    if (StringUtils.isNotBlank(qyList.get(0).getFqmfj())) {
                        String fileUrl = this.getMinioFileStreamTest(qyList.get(0).getFqmfj().split("\\?id=")[1]);
                        if (StringUtils.isNotBlank(fileUrl)) {
                            pictureRenderDataQyFzr = Pictures.ofStream(new FileInputStream(fileUrl), PictureType.JPEG)
                                    .size(width, height).create();
                        }
                    }
                }

            }
        }catch (Exception e){
            log.error("现场检查报告-相关签名-根据现场检查会议错误：{}", e.getMessage());
        }

        parMap.put("zxQm", pictureRenderDataZxry); // 中心
        parMap.put("zzQm", pictureRenderDataZz); // 组长
        parMap.put("qyfzrQm", pictureRenderDataQyFzr); // 企业负责人
        parMap.put("zyList", pictureList__zy); // 组员
        parMap.put("jcyList", pictureList_jcy); // 检查组
        parMap.put("gcyList", pictureList_gcy); // 观察员

        return parMap;
    }

    /** 初始化-现场检查纪律-根据现场检查会议相关信息
     * @param schyMap 首次会议相关 jcyList/gcyList/qyList/hy
     * */
    public String initXcjcjlByHyxx(String sqsxid, Map schyMap){
        HashMap<String, Object> parMap = new HashMap<>();
        ConfigureBuilder builder = Configure.builder();

        SpcySqsxBasic sqsx = spcySqsxBaiscService.selectSqsxInfoById(sqsxid);

        /** 事项信息 */
        String fqymc = "";
        String fywflcode = "";
        if (sqsx != null) {
            fqymc = sqsx.getFqymc();
            fywflcode = sqsx.getFywflcode();
        }
        /** 宣读人 */
        PictureRenderData pictureRenderDataXdr = null;
        /** 企业负责人 */
        PictureRenderData pictureRenderDataQyFzr = null;
        String hysj = "";
        List<Map<String, PictureRenderData>> pictureList_jcy = new ArrayList<>();
        List<Map<String, PictureRenderData>> pictureList_gcy = new ArrayList<>();

        int width = 80;
        int height = 40;
        try {
            if (schyMap != null){
                SpcySqsxHyzt hy = (SpcySqsxHyzt) schyMap.get("hy");
                List<SpcySqsxHymx> jcyList = (List<SpcySqsxHymx>) schyMap.get("jcyList");
                List<SpcySqsxHymx> gcyList = (List<SpcySqsxHymx>) schyMap.get("gcyList");
                List<SpcySqsxHymx> qyList = (List<SpcySqsxHymx>) schyMap.get("qyList");


                hysj = DateConversionUtils.DateToStringNew(hy.getFhysj());

                for (SpcySqsxHymx bean : jcyList){

                    if (StringUtils.isNotBlank(bean.getFqmfj())){
                        String fileUrl = this.getMinioFileStreamTest(bean.getFqmfj().split("\\?id=")[1]);
                        if (StringUtils.isNotBlank(fileUrl)) {

                            if (StringUtils.isNotBlank(bean.getFjcsf())
                                    && bean.getFjcsf().equals("组长")
                                    && pictureRenderDataXdr == null){
                                pictureRenderDataXdr = Pictures.ofStream(new FileInputStream(fileUrl), PictureType.JPEG)
                                        .size(width, height).create();
                            }

                            Map<String, PictureRenderData> picture = new HashMap<>();
                            try {
                                picture.put("picture", Pictures.ofStream(new FileInputStream(fileUrl), PictureType.JPEG)
                                        .size(width, height).create());
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }
                            pictureList_jcy.add(picture);
                        }
                    }
                }

                for (SpcySqsxHymx bean : gcyList){
                    if (StringUtils.isNotBlank(bean.getFqmfj())){
                        String fileUrl = this.getMinioFileStreamTest(bean.getFqmfj().split("\\?id=")[1]);
                        if (StringUtils.isNotBlank(fileUrl)) {
                            Map<String, PictureRenderData> picture = new HashMap<>();
                            try {
                                picture.put("picture", Pictures.ofStream(new FileInputStream(fileUrl), PictureType.JPEG)
                                        .size(width, height).create());
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }
                            pictureList_gcy.add(picture);
                        }
                    }
                }

                if (CollectionUtil.isNotEmpty(qyList)){
                    if (StringUtils.isNotBlank(qyList.get(0).getFqmfj())) {
                        String fileUrl = this.getMinioFileStreamTest(qyList.get(0).getFqmfj().split("\\?id=")[1]);
                        if (StringUtils.isNotBlank(fileUrl)) {
                            pictureRenderDataQyFzr = Pictures.ofStream(new FileInputStream(fileUrl), PictureType.JPEG)
                                    .size(width, height).create();
                        }
                    }
                }

            }
        }catch (Exception e){
            log.error("现场检查纪律-会议相关信息初始化出错：{}", e.getMessage());
        }

        parMap.put("fqymc", fqymc);
        parMap.put("gcyDate", hysj);
        parMap.put("qyDate", hysj);
        parMap.put("xdr", pictureRenderDataXdr);
        parMap.put("qyfzr", pictureRenderDataQyFzr);
        parMap.put("jcyList", pictureList_jcy);
        parMap.put("gcyList", pictureList_gcy);

        String orgUrl = businessConstant.UPLOAD_FILE_ROOT + "/" + WjmlConstant.getXcjcjlTemplateUrl(fywflcode);
        String destWordUrl = localFileUploadUtils.getTempFileRootUrl() + "/";
        destWordUrl += GetUuIdUtils.NotReplaceUuId() + Util.getWjHz(orgUrl);
        WordDocxReplaceUtils.docxConfigureReplace(orgUrl, destWordUrl, builder.useSpringEL().build(), parMap);

        return destWordUrl;
    }

    /** 初始化-现场检查纪律-html转换文件-下载 */
    public void downXcjcjlHtmlConvertFile(String sqsxid, Map schyMap, HttpServletResponse response){
        String destWordUrl = "";
        try {
            destWordUrl = this.initXcjcjlByHyxx(sqsxid, schyMap);
        }catch (Exception e){
            log.error("初始化-现场检查纪律-根据现场检查会议相关信息出错！{}", e.getMessage());
        }

        if (StringUtils.isNotBlank(destWordUrl)) {
            localFileUploadUtils.ejzLocalFileByZdyFile(new File(destWordUrl), response);
        }
    }

    /** 初始化申请事项文件记录 */
    private void initSqsxWjjl(String sqsxid, String type, String fwjlx, String wjxsmc, String wjccmc, String cflj){
        spcySqsxWjjlService.intiAndSaveInitSqsxWjjl(sqsxid, type, fwjlx, wjxsmc, wjccmc, cflj);
    }

    /** 根据文件id-下载文件流到本地
     * @return 文件绝对路径
     * */
    private String getMinioFileStreamTest(String fileId){
        return this.getMinioFileStreamTest(fileId, "");
    }
    private String getMinioFileStreamTest(String fileId, String fpid) {
        /*if (StringUtils.isBlank(fileId)) {
            return null;
        }*/

        SpcySqsxWjjl wjjl = null;
        if (StringUtils.isNotBlank(fileId)) {
            wjjl = spcySqsxWjjlService.getById(fileId);


        } else if (StringUtils.isNotBlank(fpid)) {
            List<SpcySqsxWjjl> qmList = spcySqsxWjjlService.findUserQmList(fpid);
            if (CollectionUtil.isNotEmpty(qmList)) {
                wjjl = qmList.get(0);
            }
        }

        if (wjjl == null || StringUtils.isBlank(wjjl.getFcflj())) {
            return null;
        }

        if (localFileUploadUtils.isEnableMinioWjjlFile()){
            InputStream inputStream = null;
            if (StringUtils.isNotBlank(wjjl.getFwjlx1()) && wjjl.getFwjlx1().equals(BusinessConstant.USER_QM)) {
                inputStream = spcyMinioUtils.getObject(localFileUploadUtils.getUserQmRelaviteUrl(wjjl.getFcflj()));
            } else {
                inputStream = spcyMinioUtils.getObject(wjjl.getFcflj());
            }
            if (inputStream == null) {
                return null;
            }

            File file = localFileUploadUtils.asFile(inputStream, Util.getWjHz(wjjl.getFcflj()));
            return file.getAbsolutePath();
        }

        if (StringUtils.isNotBlank(wjjl.getFwjlx1()) && wjjl.getFwjlx1().equals(BusinessConstant.USER_QM)) {
            return localFileUploadUtils.getUserQmAbsUrl(wjjl.getFcflj());
        }
        return localFileUploadUtils.getZdyFileAbsUrl(wjjl.getFcflj());
    }


    /**
     * 复制当前事项的附件到其他事项
     * @param copyFileId 复制文件id
     * @param targetSqsxId 目标事项id
     * */
    public Result copySqsxWjjlToOtherSqsx(String copyFileId, String targetSqsxId){
        if (StringUtils.isBlank(copyFileId)){
            return Result.error("文件参数为空！");
        }
        if (StringUtils.isBlank(targetSqsxId)){
            return Result.error("目标参数为空！");
        }

        SpcySqsxWjjl copyFj = spcySqsxWjjlService.getById(copyFileId);
        if (copyFj == null){
            return Result.error("没有相匹配的附件数据！");
        }

        String newwjccmc = GetUuIdUtils.NotReplaceUuId() + copyFj.getFwjlx();
        String newcflj = "/" + DateConversionUtils.DateToMonthTwo(new Date()) + "/" + newwjccmc;

        /** 推送并复制附件 */
        boolean flag = this.copySqsxFileStream(copyFj.getFcflj(), newcflj);
        if (flag) {
            SpcySqsxWjjl newFj = new SpcySqsxWjjl();
            BeanUtil.copyProperties(copyFj, newFj);
            newFj.setId(GetUuIdUtils.NotReplaceUuId());
            newFj.setFpid(targetSqsxId);
            newFj.setFcflj(newcflj);
            newFj.setFjdcflj("");
            newFj.setFwjccmc(newwjccmc);
            spcySqsxWjjlService.save(newFj);
        }else {
            return Result.error("附件操作失败！");
        }

        return Result.ok();
    }

    /**
     * 复制申请事项附件
     * @param copyRelativeUrl 源文件相对路径
     * @param targetCflj 新增存放相对路径
     */
    private boolean copySqsxFileStream(String copyRelativeUrl, String targetCflj){

        String outFilePath = "";
        if (localFileUploadUtils.isEnableMinioWjjlFile()) {
            InputStream minioInput = spcyMinioUtils.getObject(localFileUploadUtils.getSqsxWjjlRelativeUrl(copyRelativeUrl));
            if (minioInput == null){
                return false;
            }
            File file = localFileUploadUtils.asFile(minioInput, Util.getWjHz(copyRelativeUrl));
            outFilePath = file.getAbsolutePath();
        }else {
            outFilePath = localFileUploadUtils.getSqsxWjjlAbsUrl(copyRelativeUrl);
        }

        /** 复制文件 */
        return busService.uploadMinioFileWjjl(targetCflj, outFilePath);
    }

    /**
     * 推送已经移送的数据的事项文件模板-推送到文件桶
     */
    @Async(value = "asyncSimpleTask")
    public void pushYsSqsxWjmbToFileBucket(String sqsxid){
        /** 如果已经使用桶了就不进行推送了 */
        if (localFileUploadUtils.isEnableMinioWjmbFile()){
            return;
        }

        List<SpcyRsWjmb> list = spcyRsWjmbService.list(new LambdaQueryWrapper<SpcyRsWjmb>()
                .eq(SpcyRsWjmb::getFsqsxid, sqsxid)
                .eq(SpcyRsWjmb::getFmblx1, WjmlConstant.xcjcbg));

        for (SpcyRsWjmb wjmb : list){
            String wjmbUrl = localFileUploadUtils.getWjmbAbsUrl(wjmb.getFcflj());

            String objName = "/" + SpcyConstant.WJMB_SQSX_FILE_BASE_URL + wjmb.getFcflj();
            boolean flag = spcyMinioUtils.putFlagFile(objName, new File(wjmbUrl), wjmb.getFwjlx());
            if (flag){
                wjmb.setFbz(SpcyConstant.WJMB_SQSX_FILE_BASE_URL);
                spcyRsWjmbService.updateById(wjmb);

                // 删除本地文件
                localFileUploadUtils.deleteLocalWjmbFileUrl(wjmb.getFcflj());
            }
        }

    }

    /**
     * 现场检查-检查情况专述-验证是否完成
     */
    public HttpResult verifyXcjcJcqkzsCompleteState(String sqsxid){

        return HttpResultVo.HttpResultGet(spcyRsYwzdxxService.querySqsxXcjcJcqkzsCompleteState(sqsxid, false, false));
    }

    /**
     * 现场检查-检查情况专述-点击完成/重新编辑
     * @param wcState true: 点击完成：false: 重新编辑
     */
    public HttpResult updateXcjcJcqkzsCompleteState(String sqsxid, boolean wcState){

        if (wcState){

            /*SpcySqsxBasic sqsx = spcySqsxBaiscService.selectSqsxInfoById(sqsxid);
            if (sqsx != null && StringUtils.isBlank(sqsx.getFjcqkzs())){
                return HttpResult.error("请填写并保存检查情况描述！");
            }*/

            spcyRsYwzdxxService.querySqsxXcjcJcqkzsCompleteState(sqsxid, true, true);

        }else {
            spcyRsYwzdxxService.querySqsxXcjcJcqkzsCompleteState(sqsxid, true, false);
        }

        return HttpResult.ok("操作成功");
    }

    /**
     * 现场检查-发现问题-验证是否完成
     */
    public HttpResult verifyXcjcFxwtCompleteState(String sqsxid){

        return HttpResultVo.HttpResultGet(spcyRsYwzdxxService.querySqsxXcjcFxwtQxCompleteState(sqsxid, false, false));
    }

    /**
     * 现场检查-发现问题-点击完成/重新编辑
     * @param wcState true: 点击完成：false: 重新编辑
     */
    public HttpResult updateXcjcFxwtCompleteState(String sqsxid, boolean wcState){

        if (wcState){

            spcyRsYwzdxxService.querySqsxXcjcFxwtQxCompleteState(sqsxid, true, true);
            try {
//                busService.initCommonSqsxWjmb(sqsxid, WjmlConstant.xcjcqxjlb, "");
//                verifyAutoFileGzByCommon(sqsxid, WjmlConstant.xcjcqxjlb);
            }catch (Exception e){
            log.error("现场检查-发现问题-点击完成/重新编辑-错误：{}", e.getMessage());
            }


        }else {
            spcyRsYwzdxxService.querySqsxXcjcFxwtQxCompleteState(sqsxid, true, false);

            this.deleteOnlineSqsxFileBySqsxId(sqsxid, WjmlConstant.xcjcqxjlb, true); // 删除文件
        }

        return HttpResult.ok("操作成功");
    }

    /**
     * 现场检查-检查结论-验证是否完成
     */
    public HttpResult verifyXcjcCyjlCompleteState(String sqsxid){

        return HttpResultVo.HttpResultGet(spcyRsYwzdxxService.querySqsxXcjcJcjlCompleteState(sqsxid, false, false));
    }

    /**
     * 现场检查-检查结论-点击完成/重新编辑
     * @param wcState true: 点击完成：false: 重新编辑
     */
    public HttpResult updateXcjcCyjlCompleteState(String sqsxid, boolean wcState){

        if (wcState){

            /*SpcySqsxBasic sqsx = spcySqsxBaiscService.selectSqsxInfoById(sqsxid);
            if (sqsx != null && StringUtils.isBlank(sqsx.getFcyjl())){
                return HttpResult.error("请填写并保存检查结论！");
            }*/

            spcyRsYwzdxxService.querySqsxXcjcJcjlCompleteState(sqsxid, true, true);
            try {
//                busService.initXcjcbg(sqsxid, WjmlConstant.xcjcbg, "");
//                verifyAutoFileGzByCommon(sqsxid, WjmlConstant.xcjcbg);
            }catch (Exception e){
                log.error("现场检查-检查结论-点击完成/重新编辑-错误：{}", e.getMessage());
            }


        }else {
            spcyRsYwzdxxService.querySqsxXcjcJcjlCompleteState(sqsxid, true, false);
            this.deleteOnlineSqsxFileBySqsxId(sqsxid, WjmlConstant.xcjcbg, true); // 删除文件
        }

        return HttpResult.ok("操作成功");
    }

    /**
     * 综合评定-审查意见-验证是否完成
     */
    public HttpResult verifyZhpdScyjCompleteState(String sqsxid){

        return HttpResultVo.HttpResultGet(spcyRsYwzdxxService.querySqsxZhpdScyjCompleteState(sqsxid, false, false));
    }

    /**
     * 综合评定-审查意见-点击完成/重新编辑
     * @param wcState true: 点击完成：false: 重新编辑
     */
    public HttpResult updateZhpdScyjCompleteState(String sqsxid, boolean wcState){

        if (wcState){

            spcyRsYwzdxxService.querySqsxZhpdScyjCompleteState(sqsxid, true, true);

        }else {
            spcyRsYwzdxxService.querySqsxZhpdScyjCompleteState(sqsxid, true, false);
        }

        return HttpResult.ok("操作成功");
    }

    /**
     * 综合评定-报告书-验证是否完成
     */
    public HttpResult verifyZhpdBgsCompleteState(String sqsxid){

        return HttpResultVo.HttpResultGet(spcyRsYwzdxxService.querySqsxZhpdBgsCompleteState(sqsxid, false, false));
    }

    /**
     * 综合评定-报告书-点击完成/重新编辑
     * @param wcState true: 点击完成：false: 重新编辑
     */
    public HttpResult updateZhpdBgsCompleteState(String sqsxid, boolean wcState){

        if (wcState){

            spcyRsYwzdxxService.querySqsxZhpdBgsCompleteState(sqsxid, true, true);
            try {
                busService.initZhpdbgs(sqsxid, WjmlConstant.zhpdbgs, "");
            }catch (Exception e){
                log.error("综合评定-报告书-点击完成/重新编辑-错误：{}", e.getMessage());
            }

        }else {
            spcyRsYwzdxxService.querySqsxZhpdBgsCompleteState(sqsxid, true, false);
            this.deleteOnlineSqsxFileBySqsxId(sqsxid, WjmlConstant.zhpdbgs); // 删除文件
        }

        return HttpResult.ok("操作成功");
    }

    /**
     * 删除在线申请事项文件记录（在线生成）
     * @param sqsxid
     * @param type
     */
    private void deleteOnlineSqsxFileBySqsxId(String sqsxid, String type){
        this.deleteOnlineSqsxFileBySqsxId(sqsxid, type, false);
    }
    private void deleteOnlineSqsxFileBySqsxId(String sqsxid, String type, boolean isAll){
        List<SpcySqsxWjjl> wjList = null;
        if (isAll){
            wjList = spcySqsxWjjlService.list(new LambdaQueryWrapper<SpcySqsxWjjl>()
                    .eq(SpcySqsxWjjl::getFpid, sqsxid)
                    .eq(SpcySqsxWjjl::getFwjlx1, type));
        }else {
            wjList = spcySqsxWjjlService.list(new LambdaQueryWrapper<SpcySqsxWjjl>()
                    .eq(SpcySqsxWjjl::getFpid, sqsxid)
                    .eq(SpcySqsxWjjl::getFwjlx1, type)
                    .eq(SpcySqsxWjjl::getFwjlx3, SpcyCommonConstant.SQSX_WJJL_TYPE3_ZZZ));
        }

        if (CollectionUtil.isNotEmpty(wjList)) {
            for (SpcySqsxWjjl wjjl : wjList) {
                spcySqsxWjjlService.removeById(wjjl.getId());

                if (StringUtils.isNotBlank(wjjl.getFcflj())) {
                    localFileUploadUtils.deleteLocalFileUrl(wjjl.getFcflj());
                }

                if (StringUtils.isNotBlank(wjjl.getFjdcflj())) {
                    localFileUploadUtils.deleteLocalFileUrl(wjjl.getFjdcflj());
                }
            }
        }
    }

    /** 通用删除申请事项文件 */
    public void deleteCommontSqsxFile(String fpid, String type){
        List<SpcySqsxWjjl> list = spcySqsxWjjlService.list(new LambdaQueryWrapper<SpcySqsxWjjl>()
                .eq(SpcySqsxWjjl::getFpid, fpid)
                .eq(SpcySqsxWjjl::getFwjlx1, type));
        this.deleteCommonSqsxFile(list);
    }

    /** 删除通用文件 */
    public boolean deleteCommonSqsxFile(List<SpcySqsxWjjl> wjList){
        if (CollectionUtils.isEmpty(wjList)) {
            return true;
        }

        boolean delFlag = false;
        for (SpcySqsxWjjl oldWj : wjList) {

            boolean flag = spcySqsxWjjlService.removeById(oldWj.getId());
            if (flag){
                if (!delFlag) {
                    delFlag = true;
                }
            }

            if (StringUtils.isNotBlank(oldWj.getFcflj())) {
                localFileUploadUtils.deleteLocalFileUrl(oldWj.getFcflj());
            }
            if (StringUtils.isNotBlank(oldWj.getFjdcflj())) {
                localFileUploadUtils.deleteLocalFileUrl(oldWj.getFjdcflj());
            }
        }

        return delFlag;
    }

    /**
     * 数据修订同步相关文件内容
     * */
    @Async(value = "asyncNormalTask")
    public Result syncJcyInfoFileBySjxd(String sqsxid){

        try {
            busService.initXpxcscydh(sqsxid, WjmlConstant.xpxcscydh, ""); // 初始化文件记录
        }catch (Exception e){
            log.error("数据修订同步相关文件内容-错误: {}", e.getMessage());
        }

        try {
            busService.deleteXgInitScFile("", sqsxid, WjmlConstant.xpxcgcydh);
            busService.initXpxcgcydh(sqsxid, WjmlConstant.xpxcgcydh, ""); // 初始化文件记录
        }catch (Exception e){
            log.error("数据修订同步相关文件内容-错误: {}", e.getMessage());
        }

        verifyAutoFileGzByCommon(sqsxid, WjmlConstant.xpxcscydh, WjmlConstant.xpxcgcydh);

        return Result.ok();
    }

    /**
     * 替换-现场检查报告-文件-中心签名关键字
     * */
    public Result syncXcjcbgReplaceZxqm(String sqsxid){

        if (spcyRsYwzdxxService.verifySfyjOperation(sqsxid, true)){
            return Result.error("已经操作过了！");
        }

        List<SpcySqsxWjjl> xcjcbgList = spcySqsxWjjlService.list(new LambdaQueryWrapper<SpcySqsxWjjl>()
                .eq(SpcySqsxWjjl::getFpid, sqsxid)
                .eq(SpcySqsxWjjl::getFwjlx1, WjmlConstant.xcjcbg));

        if (CollectionUtil.isEmpty(xcjcbgList)){
            return Result.error("操作失败，没有相关文件记录！");
        }

        String errorMsg = "";
        for (SpcySqsxWjjl jcbg : xcjcbgList){

            /**合并事项、手动上传、已签字：文件不处理 */
            if (StringUtils.isNotBlank(jcbg.getFwjlx4()) && jcbg.getFwjlx4().equals(SpcyCommonConstant.SQSX_WJJL_TYPE4_SDSC)){
                continue;
            }
            if (StringUtils.isNotBlank(jcbg.getFwjlx6()) && jcbg.getFwjlx6().equals(SpcyCommonConstant.QY_WJCL_FBZ_HBSX)){
                continue;
            }
            if (StringUtils.isNotBlank(jcbg.getFwjnr()) && jcbg.getFwjnr().equals("已签字")){
                continue;
            }

            if (StringUtils.isNotBlank(errorMsg)){
                errorMsg += "\n";
            }

            String oldCflj = "";
            String sqsxMbUrl = "";
            String wjlx = jcbg.getFwjlx();
            if (jcbg.getFwjlx().equals(".pdf")){

                if (StringUtils.isBlank(jcbg.getFjdcflj())) {
                    errorMsg += "PDF文件没有对应的docx文档，请手动进行签名并回传！";
                    continue;
                }

                oldCflj = jcbg.getFjdcflj();
                sqsxMbUrl = jcbg.getFjdcflj();
                wjlx = Util.getWjHz(jcbg.getFjdcflj());
            }else if (jcbg.getFwjlx().equals(".doc") || jcbg.getFwjlx().equals(".docx")){

                sqsxMbUrl = jcbg.getFcflj();
                wjlx = jcbg.getFwjlx();

                if (StringUtils.isNotBlank(jcbg.getFjdcflj())){
                    oldCflj = jcbg.getFjdcflj();
//                    sqsxMbUrl = oldCflj;
//                    wjlx = Util.getWjHz(oldCflj);
                }
            }

            // 不处理
            if (wjlx.equals(".pdf")){
                continue;
            }

            /** 提取文件 */
            if (wjlx.equals(".doc") || wjlx.equals(".docx")){
                if (localFileUploadUtils.isEnableMinioWjjlFile()) {
                    File file = localFileUploadUtils.convertMinioToFile(localFileUploadUtils.getSqsxWjjlRelativeUrl(sqsxMbUrl),wjlx);
                    if (file != null){
                        sqsxMbUrl = file.getAbsolutePath();
                    }else {
                        errorMsg += "文件获取失败，请手动进行签名并回传！";
                        continue;
                    }
                }else {
                    sqsxMbUrl = localFileUploadUtils.getSqsxWjjlAbsUrl(sqsxMbUrl);
                }
            }

            /** doc转docx */
            if (wjlx.equalsIgnoreCase(".doc")){
                String outUrl = localFileUploadUtils.getTempFileRootUrl() + "/" + GetUuIdUtils.NotReplaceUuId() + ".docx";
                try {
                    WordPdfUtils.wordToDocx(sqsxMbUrl, outUrl);
                    sqsxMbUrl = outUrl;
                    wjlx = ".docx";
                }catch (Exception e){
                    log.error("doc文档转docx文档错误：{}", e.getMessage());

                    errorMsg += "文档转换失败，请手动进行签名并回传！";
                    continue;
                }
            }

            /** 查询文档中是否存在关键字 */
            boolean zxQm = WordDocxReplaceUtils.searchKeywordInDocx(sqsxMbUrl, "${data.@zxQm}");
            if (!zxQm){
                errorMsg += "当前文件中不存在中心签名关键字【 ${data.@zxQm} 】，请手动进行签名并回传！";
                continue;
            }

            String wjccmc = GetUuIdUtils.ReplaceUuId() + wjlx;
            String ml = "/" + DateConversionUtils.DateToMonthTwo(new Date());
            busService.initLocalTempFileMl(ml);
            String cflj = ml + "/" + wjccmc;

            String outFilePath = localFileUploadUtils.getTempFileRootUrl() + cflj;
            HashMap<String, Object> parMap = new HashMap<>();

            /** 主办人 */
            int width = 80;
            int height = 40;

            /** 中心人员 */
            PictureRenderData pictureRenderDataZxry = null;

            // 主办人
            SqsxZbrVo zbrVo = spcySqsxBaiscService.selectFzbrById(sqsxid);
            if (zbrVo != null && StringUtils.isNotBlank(zbrVo.getFzbr())){
                String id = StringPatternUtils.getStringsByIds(zbrVo.getFzbr())[0];
                String fileUrl = this.getMinioFileStreamTest("", id);
                if (StringUtils.isBlank(fileUrl)){
                    errorMsg += zbrVo.getFjbrmc() + "系统不存在签名！请手动进行签名回传 或者 前往个人信息上传签名再次重试！";
                    continue;
                }

                try {
                    pictureRenderDataZxry = Pictures.ofStream(new FileInputStream(fileUrl), PictureType.JPEG)
                            .size(width, height).create();
                } catch (FileNotFoundException e) {
                    log.error("替换现场检查报告-中心签名关键字-生成签字错误：{}", e.getMessage());

                    errorMsg += "签字生成错误，请手动进行签名并回传！";
                    continue;
                }

            }

            parMap.put("zxQm", pictureRenderDataZxry); // 中心
            parMap.put("nowTime", new TextRenderData("000000", DateConversionUtils.DateToStringNew(new Date())));

            ConfigureBuilder builder = Configure.builder();
            builder.buildGramer("${data.", "}");
            WordDocxReplaceUtils.docxConfigureReplace(sqsxMbUrl, outFilePath, builder.useSpringEL(false).build(), parMap);

            // 上传文件
            if (busService.uploadMinioFileWjjl(cflj, outFilePath)) {

                jcbg.setFjdcflj(jcbg.getFcflj());
                jcbg.setFcflj(cflj);
                jcbg.setFwjlx(wjlx);
                jcbg.setFwjccmc(wjccmc);
                jcbg.setFwjlx3(SpcyCommonConstant.SQSX_WJJL_TYPE3_ZZZ);
                jcbg.setFwjnr("已签字");

                if (spcySqsxWjjlService.updateById(jcbg)){
                    if (StringUtils.isNotBlank(oldCflj)){
                        localFileUploadUtils.deleteLocalFileUrl(oldCflj);
                    }
                }

                try {
                    /*String ml = "/" + DateConversionUtils.DateToMonthTwo(new Date());
                    busService.initLocalTempFileMl(ml);*/

                    hnCaUtils.sqsxFileToMinioGz(jcbg, ml, false);
                }catch (Exception e){
                    log.error("文件id： {}; 替换现场检查报告-中心签名关键字-盖章失败：{}", jcbg.getId(), e.getMessage());

                    /*errorMsg += "文件转换pdf失败，" + e.getMessage();
                    continue;*/
                }
            }else {

                log.error("替换现场检查报告-中心签名关键字-上传文件错误！文件id: {}", jcbg.getId());

                errorMsg += "文件存储失败，请手动进行签名并回传！";
                continue;
            }
        }

        if (StringUtils.isNotBlank(errorMsg)){
            return Result.error("操作失败，" + errorMsg);
        }

        return Result.ok();
    }

    /**
     * 验证检查报告文件记录是否已经签字
     * @return 0: 未签字; 1: 已签字
     */
    public Integer verifySfQzByJcbg(String sqsxid) {
        if (StringUtils.isBlank(sqsxid)){
            return 0;
        }

        /*if (CollectionUtil.isNotEmpty(spcySqsxWjjlService.verifySfQzWjjl(sqsxid, WjmlConstant.xcjcbg) ) ){
            return 1;
        }*/
        if (spcyRsYwzdxxService.verifySfyjOperation(sqsxid, false)){
            return 1;
        }

        return 0;
    }

    /** 初始化检查缺陷调整通知书 */
    public SpcySqsxWjjl initJcqxTzs(String sqsxid, SpcySqsxBasic sqsx, String type, String wjxsmc, String relativePath){
        if (sqsx == null){
            sqsx = spcySqsxBaiscService.selectSqsxById(sqsxid);
        }
        String fywflcode = sqsx.getFywflcode();
        String wjmbUrl = "";
        SqsxWjmbVo wjmbBySqsxId = busService.getWjmbBySqsxId("", sqsxid, sqsx, fywflcode, type);
        if (StringUtils.isBlank(wjmbBySqsxId.getErrorMsg())){
            wjmbUrl = wjmbBySqsxId.getWjmbUrl();
        }else {
            // 模板路径
            wjmbUrl = businessConstant.UPLOAD_FILE_ROOT + "/" + relativePath;
        }

        String wjlx = Util.getWjHz(wjmbUrl); // 获取文件路径的 文件类型
        String formatType = BusinessConstant.getWordFormatType(wjlx); // word替换格式

        Map<String,String> map = new HashMap<>();
        SpcySqsxWjjl newWjjl = null;

        String sjmc = ""; // 文件虚假名称
        String wjccmc = ""; // 文件存储名称

        String newDir = "/" + DateConversionUtils.DateToMonthTwo(new Date());
        busService.initLocalTempFileMl(newDir);

        String cflj = ""; // 文件存放路径

        SpcySqsxWjjl wjjl = new SpcySqsxWjjl();
        wjjl.setFpid(sqsxid);
        wjjl.setFwjlx(wjlx);
        wjjl.setFwjlx1(type);
        wjjl.setFwjlx2(SpcyCommonConstant.SQSX_WJJL_TYPE2_TBWDZ);
        wjjl.setFwjlx3(SpcyCommonConstant.SQSX_WJJL_TYPE3_ZZZ);

        String fqymc = sqsx.getFqymc();

        if (StringUtils.isBlank(wjxsmc)){
            wjxsmc = type + "-" + fqymc; // 文件显示名称
        }

        sjmc = GetUuIdUtils.NotReplaceUuId();
        wjccmc = sjmc + wjlx;
        cflj = newDir + "/" + wjccmc;
        newWjjl = new SpcySqsxWjjl();
        BeanUtil.copyProperties(wjjl, newWjjl);

        map = busService.getObjectMap(sqsxid,"", false, false); // 获取替换相关内容

        String wordText = busService.genSqsxWj(cflj, wjlx, wjmbUrl, "", formatType, map);

        newWjjl.setId(GetUuIdUtils.ReplaceUuId());
        newWjjl.setFywflcode(fywflcode);
        newWjjl.setFwjxsmc(wjxsmc);
        newWjjl.setFwjccmc(wjccmc);
        newWjjl.setFcflj(cflj);
        newWjjl.setFwjnr(wordText);
        newWjjl.setFbusid(sqsx.getFqyid());
        newWjjl.setFbusmc(wjxsmc);
        spcySqsxWjjlService.save(newWjjl);

        return newWjjl;
    }

}
